如何使QGraphicsScene的左上方与QGraphicsView的左上方重合?

How do I make the top left of a QGraphicsScene coincide with the top left of my QGraphicsView?

我总是在QGraphicsScene坐标系上遇到麻烦。 我的场景的创建非常简单,如下所示:

1
2
scene = new QGraphicsScene(this);
this->setScene(scene);

这是QGraphicsView。 现在,我想在(0,0)处绘制一个矩形。这将创建一个大致位于屏幕中间的矩形。 如何使(0,0)对应于视图的左上角? 这样我就知道在哪里可以放置任何东西...


可以尝试以下方法:QGraphicsView::setAlignment(Qt::Alignment alignment)
(看这里)

您将必须使用类似:

1
scene->setAlignment(Qt::AlignTop|Qt::AlignLeft);


@ rsp1984

这是基于QWIdget的类的头代码示例。我只是从工作中复制和粘贴与该问题有关的代码部分,因此如果它不能编译,请原谅,因为我遗漏了一些内容:

标头:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <QWidget>
#include <QGraphicsView>
#include <QDesktopWidget>
#include <QVBoxLayout>
#include <QApplication>
#include <QGraphicsScene>

class MonitorScreen : public QWidget
{
    Q_OBJECT
public:
    explicit MonitorScreen(QWidget *parent = nullptr, const QRect &screen = QRect(), qreal SCREEN_W = 1, qreal SCREEN_H = 1);
private:
    QGraphicsView *gview;  
};

CPP:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include"monitorscreen.h"

MonitorScreen::MonitorScreen(QWidget *parent, const QRect &screen, qreal SCREEN_W, qreal SCREEN_H) : QWidget(parent)
{

    // Making this window frameless and making sure it stays on top.
    this->setWindowFlags(Qt::FramelessWindowHint|Qt::WindowStaysOnTopHint|Qt::X11BypassWindowManagerHint|Qt::Window);

    this->setGeometry(screen);

    // Creating a graphics widget and adding it to the layout
    gview = new QGraphicsView(this);
    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->setContentsMargins(0,0,0,0);
    layout->addWidget(gview);

    gview->setScene(new QGraphicsScene(0,0,screen.width(),screen.height(),this));
    gview->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    gview->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

    // White background
    gview->scene()->setBackgroundBrush(QBrush(Qt::gray));
}

这里的想法是场景与QGraphcisView小部件的矩形大小相同。这样,位于100,100处的对象将是相对于QGraphicsView左上角的坐标100、100。我这样做是因为我的场景永远不会比显示它的小部件大。实际上,由于我的特殊问题,它们需要大小相同。

请记住,您可以拥有更大(或更小)的场景。如果您的场景较大,则不会绘制带有可见视图的对象,但它们仍将存在于内存中。

但是,我一直发现这样做可以极大地方便您开始在任何给定项目中定位和调整项目大小,因为您现在知道100%确定在任何给定位置应该出现的位置。然后,您可以开始编码更复杂的行为。

我希望这有帮助!