QGraphicsScene的奇怪问题

时间:2018-06-07 06:19:45

标签: c++ qt qt5 qgraphicsview qgraphicsscene

我的目标:       我想在QGraphicsView上绘制一个长度和宽度为100的简单矩形,位置x = 0,y = 0。这看起来应该是这样的 This is how I want

到目前为止我做了什么 我在主页(MainWindow)的构造函数中创建了一个名为block_realiser的对象(在堆上),它接受QGraphicsView作为构造函数中的参数。我在块实现器构造函数中创建了一个QGraphicsScene(在堆上),并在其构造函数本身中将此场景设置为视图。在block_realiser中有一个名为drawRect的函数,它应该在(0,0)处绘制一个100x100的矩形。 代码是

Block_Realiser::Block_Realiser(QGraphicsView *view, QObject *parent) :
    QObject(parent)
{
    m_View = view;
    m_Scene = new QGraphicsScene;
    m_View->setScene(m_Scene);
}

void Block_Realiser::drawRect()
{
    m_Scene->addRect(m_View->x(), m_View->y(),
                 100, 100);
}

现在遇到我的问题。在主页的构造函数中有两种调用函数drawRect的方法。一个是通过计时器(延迟100毫秒后),另一个是直接呼叫 1)通过计时器,代码是

HomePage::HomePage(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::HomePage)
{
    ui->setupUi(this);
    realiser = new Block_Realiser(ui->graphicsView);

    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), realiser, SLOT(drawRect()));
    connect(timer, SIGNAL(timeout()), timer, SLOT(deleteLater()));
    timer->setSingleShot(true);
    timer->start(100);
}

输出

enter image description here

2)直接调用函数

代码是

HomePage::HomePage(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::HomePage)
{
    ui->setupUi(this);
    realiser = new Block_Realiser(ui->graphicsView);
    realiser->drawRect();
}

输出是 enter image description here

所以有人可以解释一下上述两种情况的情况吗?我怎样才能实现我的目标?我之前已经将qwidget子类化了,并重新实现了它的paintEvent,以实现与我的目标相同的结果。但这并不是在qgraphicsscene中发生的。请帮帮我。如果遗漏任何细节,请告诉我。

2 个答案:

答案 0 :(得分:1)

AddRect坐标是相对于项目的,而不是相对于包含qgraphicscene的小部件。

你应该致电

  m_Scene->addRect(0,0,100,100);

答案 1 :(得分:1)

视图位置在显示时重新计算。使用计时器时,m_View->x()m_View->y()值可能与您直接调用drawRect方法时的值不同。这将意味着不同的宽度和高度值。我不明白为什么你使用视图位置+ 100来计算你的大小。

如果您希望矩形位于左上角,只需将alignment设置为您的视图:

m_View->setAlignment(Qt::AlignLeft | Qt::AlignTop);