QGraphicsScene scaled weirdly in QGraphicsView

对着背影说爱祢 提交于 2019-12-06 06:00:53

问题


I'm messing around with QGraphicsView and QGraphicsScene to create a Tic Tac Toe clone. I add some QGraphicsLineItems 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 appropriately. This works fine, except for the first time that I run the program:

Once I resize the window by any amount, the scene is scaled correctly:

Here's 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've tried adding a call to fitInView at the end of TestApp's constructor, but it doesn't seem to do anything - resizeEvent seems to be called once at the start of the program's execution anyway.

Cheers.


回答1:


Handle the view fit also inside the showEvent:

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


来源:https://stackoverflow.com/questions/9858971/qgraphicsscene-scaled-weirdly-in-qgraphicsview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!