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

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

我总是对 QGraphicsScene 坐标系有问题。我的场景是这样创建的:

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

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

你可以试试这个方法:QGraphicsView::setAlignment(Qt::Alignment alignment) (see here)

你必须使用类似的东西:

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

@rsp1984

这里是一个基于 QWIdget 的 class 的 header 代码示例。我只是从工作中复制和粘贴与问题相关的代码部分,所以如果它没有编译,请原谅,因为我遗漏了一些东西:

Header:

#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;  
};

菲律宾共产党:

#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。我这样做是因为我的场景永远不会比显示它的小部件大。事实上,由于我的特殊问题,它们需要相同的尺寸。

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

不过,我一直发现这样做可以极大地促进您在任何给定项目中开始定位和调整项目大小的方式,因为您现在可以 100% 确定在任何给定位置的某些内容应该出现在哪里。然后您可以开始编写更复杂的行为。

希望对您有所帮助!