Search code examples
c++linuxqtqpainter

Why is QPainter not drawing to my QWidget?


I'm trying to draw a line on my window but I haven't been able to get anything to actually draw.

My .h

#ifndef BOARD_H
#define BOARD_H

#include <Disc.h>
#include <iostream>
#include <QApplication>
#include <QPaintEvent>

class Board
{
    private:
        int currentDiscs;   
        Disc* discArray[64];
        char* first;
        QWidget* window;
    public:
        Board(int*);
        int StartDrawing(QApplication*);

};

#endif

}

My .cpp

int Board::StartDrawing(QApplication* app) 
{
int WIDTH = 640;
int HEIGHT = 800;

QWidget* window = new QWidget();

window->setAttribute(Qt::WA_PaintOutsidePaintEvent, true);
window->setFixedSize(WIDTH, HEIGHT);
window->setWindowTitle("Title!");

this->window = window;
window->show();

QPainter* painter = new QPainter(window);
//QPixmap pixmap1("\\images\\tile_1.png");

//painter->drawPixmap(QPoint(0,0), pixmap1);  // this works
painter->setPen(QPen(Qt::black, 12, Qt::DashDotLine, Qt::RoundCap));
painter->drawLine(10,10,100,500);
delete painter;

return app->exec();
}

My guess is that I'm missing something with my QPainter but I haven't seen anything online to suggest I need call any other functions with it.

What am I missing?

Thanks for your time.


Solution

  • It is always useful to read the documentation, yours is the most frequently made mistake:

    Each widget performs all painting operations from within its paintEvent() function. This is called whenever the widget needs to be redrawn, either as a result of some external change or when requested by the application.

    You must only paint on a widget from that widget's paint event. Other paint devices are less restricted, you can paint from everywhere to another paint device, and if needed, paint that cache to a widget in its paint event. Note that on some platforms QPixmap might not support drawing from a thread other than the main thread.