Answer the question
In order to leave comments, you need to log in
Problem with drawing on top of a widget in Qt
I did not have, in general, development experience on Qt, therefore, in order not to accidentally spoil anything, I started with an example project from the Qt website. Here is the Image Viewer project itself .
The technical essence of the project: the ImageViewer class inherits QMainWindow, sets its “central widget” to the QScrollArea scrolling area, in which the QLabel with the picture is located.
The source code is on the same page in the "Files" section at the top.
The problem is this: I wanted to do some drawing on top of the displayed image, but for the sake of example, let's reduce the task to just drawing a line.
Armed with Google, I came up with this option: in the imageviewer.h
file , we connect the library for drawing:
#include <QPainter>
protected:
void paintEvent(QPaintEvent *);
void ImageViewer::paintEvent(QPaintEvent * e)
{
QPainter p(this);
p.drawLine(0,0,100,100);
}
setCentralWidget(scrollArea);
void ImageViewer::paintEvent(QPaintEvent * e)
{
QPainter p(scrollArea);
p.drawLine(0,0,100,100);
}
QPainter::begin: Paint device returned engine == 0, type: 1
Answer the question
In order to leave comments, you need to log in
Derivate from QLabel, override its paintEvent and in it first call QLabel::paintEvent(event); then add your own painting.
Sobsna, code:
#include <QMainWindow>
#include <QScrollArea>
#include <QLabel>
#include <QApplication>
#include <QPainter>
class MyLabel : public QLabel {
protected:
virtual void paintEvent(QPaintEvent* e) {
QLabel::paintEvent(e);
QPainter p(this);
p.setPen(Qt::green);
p.drawLine(0, 0, 100, 100);
}
};
class ImageView : public QMainWindow {
public:
ImageView() : QMainWindow() {
QScrollArea* scr = new QScrollArea();
setCentralWidget( scr );
QLabel* label = new MyLabel();
label->setPixmap(QPixmap("./moon_from_andrey.jpg"));
scr->setWidget(label);
}
};
int main(int argc, char* argv[]) {
QApplication app(argc, argv);
ImageView view;
view.setGeometry(100, 100, 500, 400);
view.show();
return app.exec();
}
I somehow drew on the button like this
void PaintButtonUp::paintEvent(QPaintEvent *event)
{
QPushButton::paintEvent(event);
QPainter paint(this);
static const QPointF points[3] = {
QPointF(3.0, 25.0),
QPointF(10.0, 15.0),
QPointF(17.0, 25.0),
};
paint.setPen(QPen(Qt::darkGray, 2, Qt::SolidLine, Qt::RoundCap));
paint.setRenderHint(QPainter::Antialiasing, true);
paint.setBrush(QBrush(Qt::gray, Qt::SolidPattern));
paint.drawPolygon(points, 3);
}
: first, the standard method was called,
QPushButton::paintEvent(event);
and then I drew what I needed on the button.
I don't know if this will help you or not.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question