代码之家  ›  专栏  ›  技术社区  ›  Gurushant GeneCode

qgraphicscene的奇怪问题

  •  0
  • Gurushant GeneCode  · 技术社区  · 6 年前

    我的目标: 我想在qgraphicsview的x=0,y=0位置画一个长宽100的简单矩形。应该是这样的 This is how I want

    到目前为止我所做的 我在主页的构造函数(mainwindow)中创建了一个名为block_realler的对象(堆上),它接受qgraphicsview作为构造函数中的参数。我在block realler构造函数中创建了一个qgraphicscene(堆上),在它的构造函数中,我将这个场景设置为视图。block-realler中有一个名为draw rect的函数,它应该在(0,0)处绘制100x100的rect。 代码是

    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,以实现与我的目标相同的结果。但这并不是在qgraphicscene中发生的。请帮帮我。如果缺少任何细节,请告诉我。

    2 回复  |  直到 6 年前
        1
  •  1
  •   thuga    6 年前

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

    如果你想让你的直肠在左上角,只要设置 alignment 在您看来:

    m_View->setAlignment(Qt::AlignLeft | Qt::AlignTop);
    
        2
  •  1
  •   Sergio Monteleone    6 年前

    addrect坐标是相对于项的,而不是相对于包含qgraphicsene的小部件的。

    你应该打电话

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