Question

I want to add lines programmatically in a QLabel between two points. From what I found, it seems that the only way to do it is to subclass a QWidget to change the PaintEvent() protected method.

So, I create a new class 'QLineObject' from QWidget. This is my header file :

class QLineObject : public QWidget
{
    Q_OBJECT

public:
    QLineObject();
    QLineObject(Point from, Point to);

protected:
    void paintEvent(QPaintEvent *event);

private:
    Point fromPoint;
    Point toPoint;
};

And the implementation file :

QLineObject::QLineObject()
{
    Point point;
    point.x = 0.0;
    point.y = 0.0;

    fromPoint = point;
    toPoint = point;
}

QLineObject::QLineObject(Point from, Point to)
{
    fromPoint = from;
    toPoint = to;
}

void QLineObject::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.drawLine(fromPoint.x, fromPoint.y, toPoint.x, toPoint.y);
}

Here's come the problem. I can't find how to add this widget in my main window. If I create a new instance of QLineObject and call show(), it popup a new window. I'm sure I'm just missing something. Is there someone who want to help me? I would like to know how to create and add it from somewhere else that my main window constructor.

Thank you!

Was it helpful?

Solution

You shouldn't be calling show on the QLineObject. Instead, pass the main window as the parent to your constructor and pass that to the inherited QWidget. Then call show on the main widget, which in this case is the main window...

class QLineObject : public QWidget
{
    public:
        QLineObject(QWidget* parent);
};

QLineObject::QLineObject(QWidget* parent)
    : QWidget(parent)
{

}

QWidget* pWidget = new QWidget;
QLineObject* pLineObject = new QLineObject(pWidget);

pWidget->show();

Alternatively, you can use the QLabel as the parent.

QLabel* pLabel = new QLabel(pWidget);
QLineObject* pLineObject = new QLineObject(pLabel);
pWidget->show();

Also, you probably want to be calling QWidget::paintEvent in your overridden paintEvent.

OTHER TIPS

I would do the following:

QMainWindow mw;
QLineObject lo;
mw.setCentralWidget(&lo);
mw.show();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top