【发布时间】:2021-04-14 13:33:22
【问题描述】:
我在 qt 的网站和这里查看了一些资源,但我无法解决我的问题。
我正在尝试通过鼠标单击在 QGraphicsScene 上绘制一个矩形,并且我希望新矩形在用户单击的位置居中,但这在场景足够大之前不起作用。
这是我尝试过的
在MainWindow.cpp
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
=
ui->graphView->setContextMenuPolicy(Qt::CustomContextMenu);
scene = new QGraphicsScene();
ui->graphView->setScene(scene);
...
}
void MainWindow::on_graphView_customContextMenuRequested(const QPoint &pos)
{
auto pp= ui->graphView->mapToScene(pos);
tableOfRectangles.push_back( new component(pp,s,n,t)); //component is my class that inherits from qgraphicsitem
scene->addItem(tableOfRectangles[tableOfRectangles.size()-1]);
}
在compenent.cpp
component::component(QPointF pos,unsigned int id, QString cname, QString ctype )
{
this->center = pos;
this->id = id;
this->name = cname;
this->type = ctype;
setFlag(ItemIsMovable);
}
QRectF component::boundingRect() const
{
return QRectF(center.x(),center.y(),80,80);
}
我的问题是:
第一个矩形绘制在中间,并且随着我向正确位置添加的越多,它就会保持轻微移动。通过添加更多矩形(或拖动现有矩形)使场景足够大(当滚动条开始出现时),新矩形将正确添加到鼠标位置。但是我如何强制它们从一开始就插入到正确的位置?
【问题讨论】:
-
你检查QGrapicsView::setTransformationAnchor()了吗?当我曾经为SO: Zoom functionality using Qt 写答案时,我偶然发现了这一点。 (我在接近尾声时提到过。)
标签: c++ qt qt5 qgraphicsscene qgraphicsitem