QGraphicsScene scales weirdly in QGraphicsView

I fiddled with QGraphicsView and QGraphicsScene to create a Tic Tac Toe clone. I add a few QGraphicsLineItem to my scene and override the resizeEvent method of the widget that contains the view, so that when the window is resized, the view and its contents are scaled accordingly. This works fine, except that I run the program for the first time:

Incorrect scaling

As soon as I resize the window to any size, the scene scales correctly:

Correct scaling

Here is the code:

main.cpp:

 #include <QtGui> #include "TestApp.h" int main(int argv, char **args) { QApplication app(argv, args); TestApp window; window.show(); return app.exec(); } 

TestApp.h:

 #ifndef TEST_APP_H #define TEST_APP_H #include <QtGui> class TestApp : public QMainWindow { Q_OBJECT public: TestApp(); protected: void resizeEvent(QResizeEvent* event); QGraphicsView* view; QGraphicsScene* scene; }; #endif 

TestApp.cpp:

 #include "TestApp.h" TestApp::TestApp() : view(new QGraphicsView(this)) , scene(new QGraphicsScene(this)) { resize(220, 220); scene->setSceneRect(0, 0, 200, 200); const int BOARD_WIDTH = 3; const int BOARD_HEIGHT = 3; const QPoint SQUARE_SIZE = QPoint(66, 66); const int LINE_WIDTH = 10; const int HALF_LINE_WIDTH = LINE_WIDTH / 2; QBrush lineBrush = QBrush(Qt::black); QPen linePen = QPen(lineBrush, LINE_WIDTH); for(int x = 1; x < BOARD_WIDTH; ++x) { int x1 = x * SQUARE_SIZE.x(); scene->addLine(x1, HALF_LINE_WIDTH, x1, scene->height() - HALF_LINE_WIDTH, linePen); } for(int y = 1; y < BOARD_HEIGHT; ++y) { int y1 = y * SQUARE_SIZE.y(); scene->addLine(HALF_LINE_WIDTH, y1, scene->width() - HALF_LINE_WIDTH, y1, linePen); } view->setScene(scene); view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); view->show(); view->installEventFilter(this); setCentralWidget(view); } void TestApp::resizeEvent(QResizeEvent* event) { view->fitInView(0, 0, scene->width(), scene->height()); QWidget::resizeEvent(event); } 

I tried adding the fitInView call to the end of the TestApp constructor, but it does nothing - resizeEvent seems to be called once at the beginning of the program.

Greetings.

+4
source share
1 answer

Process the view also located in showEvent:

 void TestApp::showEvent ( QShowEvent * event ) { view->fitInView(0, 0, scene->width(), scene->height()); QWidget::showEvent(event); } 
+6
source

Source: https://habr.com/ru/post/1403303/


All Articles