0

我在使用 Qt 时遇到了一些问题。我正在尝试QRect通过paintEvent为继承QWidget并放置在QScrollArea. 问题是,paintEvent根本不会触发(不是在调整大小事件时,不是在我调用repaint()orupdate()时,也不是在我启动程序时)。这是我超载的地方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);
}

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

4

1 回答 1

1

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

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 所说,这最终是一个尺寸问题。

于 2016-01-14T16:50:12.827 回答