Note that there are some explanatory texts on larger screens.

plurals
  1. POQGraphicsScene scaled weirdly in QGraphicsView
    text
    copied!<p>I'm messing around with <code>QGraphicsView</code> and <code>QGraphicsScene</code> to create a Tic Tac Toe clone. I add some <code>QGraphicsLineItem</code>s to my scene and override the <code>resizeEvent</code> method of the Widget that contains the view, so that when the window is resized, the view and its contents are scaled appropriately. This works fine, except for the first time that I run the program:</p> <p><img src="https://i.stack.imgur.com/tmMDv.png" alt="Incorrect scaling"></p> <p>Once I resize the window by any amount, the scene is scaled correctly:</p> <p><img src="https://i.stack.imgur.com/Hxw4s.png" alt="Correct scaling"></p> <p>Here's the code:</p> <p><strong>main.cpp:</strong></p> <pre><code>#include &lt;QtGui&gt; #include "TestApp.h" int main(int argv, char **args) { QApplication app(argv, args); TestApp window; window.show(); return app.exec(); } </code></pre> <p><strong>TestApp.h:</strong></p> <pre><code>#ifndef TEST_APP_H #define TEST_APP_H #include &lt;QtGui&gt; class TestApp : public QMainWindow { Q_OBJECT public: TestApp(); protected: void resizeEvent(QResizeEvent* event); QGraphicsView* view; QGraphicsScene* scene; }; #endif </code></pre> <p><strong>TestApp.cpp:</strong></p> <pre><code>#include "TestApp.h" TestApp::TestApp() : view(new QGraphicsView(this)) , scene(new QGraphicsScene(this)) { resize(220, 220); scene-&gt;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 &lt; BOARD_WIDTH; ++x) { int x1 = x * SQUARE_SIZE.x(); scene-&gt;addLine(x1, HALF_LINE_WIDTH, x1, scene-&gt;height() - HALF_LINE_WIDTH, linePen); } for(int y = 1; y &lt; BOARD_HEIGHT; ++y) { int y1 = y * SQUARE_SIZE.y(); scene-&gt;addLine(HALF_LINE_WIDTH, y1, scene-&gt;width() - HALF_LINE_WIDTH, y1, linePen); } view-&gt;setScene(scene); view-&gt;setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); view-&gt;setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); view-&gt;show(); view-&gt;installEventFilter(this); setCentralWidget(view); } void TestApp::resizeEvent(QResizeEvent* event) { view-&gt;fitInView(0, 0, scene-&gt;width(), scene-&gt;height()); QWidget::resizeEvent(event); } </code></pre> <p>I've tried adding a call to <code>fitInView</code> at the end of <code>TestApp</code>'s constructor, but it doesn't seem to do anything - <code>resizeEvent</code> seems to be called once at the start of the program's execution anyway.</p> <p>Cheers.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload