Qt5 paintEvent 未在 QScrollArea 内调用



我在Qt上遇到了一些问题。我正在尝试使用 QRect 创建单元格的 2D 绘图,方法是重载继承QWidget并放置在QScrollArea内的自定义类的paintEvent。问题是,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);
}

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

我已经通过如下修改来修复它:

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);
}

我把油漆原封不动地留下了。正如AlexanderVX所说,这最终是一个尺寸问题。

最新更新