我总是遇到QGraphicsScene坐标系的问题。我的场景创建非常简单:
scene = new QGraphicsScene(this);
this->setScene(scene);
这是QGraphicsView。现在我想在(0,0)处绘制一个矩形。这会创建一个大致位于屏幕中间的矩形。如何使(0,0)对应于我视图的左上角?这是我知道我可以在哪里定位......
答案 0 :(得分:2)
哟可以尝试这种方法:QGraphicsView::setAlignment(Qt::Alignment alignment)
(see here)
你必须使用类似的东西:
scene->setAlignment(Qt::AlignTop|Qt::AlignLeft);
答案 1 :(得分:0)
@ rsp1984
这是基于QWIdget的类的标头代码的示例。我只是从工作中复制和粘贴与该问题相关的代码部分,因此,如果由于我遗漏了一些东西而无法编译,请原谅。
标题:
#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:
#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%确定在任何给定位置应该出现的位置。然后,您可以开始编码更复杂的行为。
我希望这会有所帮助!