0

from my main window I am launching a dialog which has a label, in which I am trying to paint.

So, the dialog's header file (.h) has two classes, one for the dialog itself and one for my label. So, my label's class is this:

class MyImage : public QLabel
{
    Q_OBJECT

public:
        explicit MyImage(QWidget *parent = 0);

protected:
    void paintEvent(QPaintEvent *e);
};

and in the .cpp, along with the constructor of my QDialog I have the constructor of my MyImage class and the paintEvent function:

MyImage::MyImage(QWidget *parent)
: QLabel(parent)
{
    /*...*/
}

void MyImage::paintEvent(QPaintEvent *e)
{
    QLabel::paintEvent(e);
    QPainter painter(image_label);
    painter.setPen(QPen(QBrush(QColor(0,0,0,180)),1,Qt::DashLine));
    painter.setBrush(QBrush(QColor(255,255,255,120)));
    painter.drawRect(selectionRect);
}

The image_label is a MyImage object. On the constructor of my QDialog I do the following so as to add it to my QDialog's layout:

mainLayout->addWidget(image_label);

But it is null. I get an error message on output (cannot add null widget) and when I try to add a pixmap to the image_label the program crashes.

Thanks in advance for any answers!

4

1 回答 1

0
void MyImage::paintEvent(QPaintEvent *e)
{
    // QPainter painter(image_label); <- Only paint onto yourself.
    QPainter painter(this);
    painter.setPen(QPen(QBrush(QColor(0,0,0,180)),1,Qt::DashLine));
    painter.setBrush(QBrush(QColor(255,255,255,120)));
    painter.drawRect(selectionRect);
}

不要调用基类,因为任何输出都会被新的QPainter. 它正在崩溃,因为它image_label是空的。

于 2012-08-16T10:47:42.247 回答