Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QPainter. Draw line

Tags:

qt

qpainter

I am trying to draw line.

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    QPainter painter(&w);
    painter.setPen(QPen(Qt::black, 12, Qt::DashDotLine, Qt::RoundCap));
    painter.drawLine(0, 0, 200, 200);

    return a.exec();
}

But there is nothing painting on the window. What is wrong?

like image 488
Ufx Avatar asked Jul 10 '14 08:07

Ufx


1 Answers

You can not paint outside of the paintEvent() function, at least on Windows and Mac OS. However you can override your MainWindow class' paintEvent() function to draw the line there. For example:

class Widget : public QWidget
{
protected:
    void paintEvent(QPaintEvent *event)
    {
        QPainter painter(this);
        painter.setPen(QPen(Qt::black, 12, Qt::DashDotLine, Qt::RoundCap));
        painter.drawLine(0, 0, 200, 200);
    }
};

And the usage:

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    Widget w;
    w.show();
    [..]
like image 79
vahancho Avatar answered Oct 21 '22 01:10

vahancho