在QScrollArea中没有调用Qt5 paintEvent

时间:2016-01-14 00:27:10

标签: c++ qt repaint paintevent

我在使用Qt时遇到了一些问题。我正在尝试使用QRect创建一个包含paintEvent的单元格的2D绘图,重载QWidget以获取继承QScrollArea并放置在paintEvent内的自定义类。问题是,repaint()根本没有触发(不是在调整大小事件时,不是在我调用update()paintEvent时,也不是在我启动程序时)。这是我在GOL.cpp中重载void GOL::paintEvent(QPaintEvent *) { QPainter painter(this); //painter.setPen(Qt::black); int x1Rect = rectPaint.x(); int y1Rect = rectPaint.y(); int x2Rect = x1Rect + rectPaint.width(); int y2Rect = y1Rect + rectPaint.height(); int xCell; int yCell = 0; for (int i = 0; i < rows; i++) { xCell = 0; for (int j = 0; j < cols; j++) { if (xCell <= x2Rect && yCell <= y2Rect && xCell + cellSize >= x1Rect && yCell + cellSize >= y1Rect) { if (principalMatrix->get(i,j)) { painter.fillRect(xCell, yCell, cellSize - 1, cellSize - 1, cellColourAlive); } else { painter.fillRect(xCell, yCell, cellSize - 1, cellSize - 1, cellColourDead); } } xCell += cellSize; } yCell += cellSize; } } 的地方:

DisplayGame.cpp

我的布局如下DisplayGame::DisplayGame(QWidget *parent, int threads_no, int generations, char* file_in, char* file_out) : QWidget(parent) { gol = new GOL(threads_no, generations, file_in, file_out); QHBoxLayout *title = setupTitle(); QHBoxLayout *buttons = setupButtons(); QVBoxLayout *layout = new QVBoxLayout(); scrlArea = new QScrollArea; scrlArea->setWidget(gol); layout->addLayout(title); layout->addWidget(scrlArea); layout->addLayout(buttons); setLayout(layout); }

{{1}}

老实说,我不知道为什么它没有画任何东西。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我通过修改如下修复了它:

DisplayGame::DisplayGame(QWidget *parent, int threads_no, int generations, char* file_in, char* file_out) :
    QWidget(parent) {

    gol = new GOL(this, threads_no, generations, file_in, file_out);

    QSize *adjustSize = new QSize(gol->cellSize, gol->cellSize); //QSize object that is as big as my QRect matrix
    adjustSize->setWidth(gol->cellSize * gol->rows);
    adjustSize->setHeight(gol->cellSize * gol->cols);
    gol->setMinimumSize(*adjustSize);

    QVBoxLayout *layout = new QVBoxLayout;

    QHBoxLayout *title = setupTitle();
    layout->addLayout(title);

    QHBoxLayout *buttons = setupButtons();
    layout->addLayout(buttons);

    QPalette pal(palette()); //Setting the background black, so the white spaces between QRect items cannot be seen (though I could have modified the margins?)
    pal.setColor(QPalette::Background, Qt::black);

    scrlArea = new QScrollArea(this);
    scrlArea->setAutoFillBackground(true);
    scrlArea->setPalette(pal);
    scrlArea->setWidget(gol);

    layout->addWidget(scrlArea);

    setLayout(layout);
}

我已经离开了paintEvent。正如AlexanderVX所说,这最终是一个尺寸问题。