c++ - 在 Qt 中选择实体

标签 c++ qt

我想让图形 View 中的实体可选择,就像我们通常选择拖动的东西一样。对于拖动问题。我使用橡皮筋功能:

   ui->graphicsView->setDragMode(QGraphicsView::RubberBandDrag);

对于可选择的实体,在每个槽(用于绘制线、圆等的槽)中,我设置了标志,但该项目未被选择。 这是代码:

void MainWindow::drawCircle(){
    ui->graphicsView->setScene(scene);
    item2 = new circle;
    scene->addItem(item2);
    qDebug() << "Circle Created";
   item2->setFlag(QGraphicsItem::ItemIsSelectable);

我该怎么做才能使实体可供选择?

最佳答案

您不需要在每个插槽中调用 setFlag(QGraphicsItem::ItemIsSelectable) 。 您应该在创建 QGraphicsItem 时设置适当的标志,或者使用指向对象的指针:-

QGraphicsItem* pItem = new QGraphicsItem(parent);
pItem->setFlag(QGraphpicsItem::ItemIsSelectable);

或者在继承的 QGraphicsItem 的构造函数中。

如果您使用的项目继承自QGraphicsItem,那么您需要正确定义其boundingRect函数。如果项目的形状不规则,那么您还可以覆盖形状函数。

如果操作正确,如 documentation RubberBandDrag 的状态:-

A rubber band will appear. Dragging the mouse will set the rubber band geometry, and all items covered by the rubber band are selected. This mode is disabled for non-interactive views.

此外,您似乎对如何使用 QGraphicsView/QGraphicsScene 系统感到困惑。 QGraphicsView 可以被认为是观察世界的窗口,即 QGraphicsScene。

创建一个场景并将场景设置到 View 一次,然后将项目添加到场景中。之后,您的用户将与 QGraphicsView 和场景交互,而不是与 MainWindow 交互。

MainWindow 只是 QGraphicsView 的一个容器。事实上,您根本不需要 MainWindow,除非 QGraphicsView/场景是具有其他小部件的较大应用程序的一部分。

当用户在 QGraphicsView 上单击鼠标时,可以在场景中拖动标记设置为可选择和可移动的项目。如果您需要更多行为,您可以覆盖 QGraphicsView 的鼠标事件(mouseMoveEvent、mousePressEvent、mouseReleaseEvent),甚至覆盖单个项目中的事件。

我建议查看 Qt examples for QGraphicsView .

关于c++ - 在 Qt 中选择实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25156146/

相关文章:

c++ - 模板模板参数默认可以引用其他模板类型参数吗?

qt - 是否有用于在Qt中显示代码分支的控件?

c++ - Qt 信号与槽 : How do I get the data which was changed?

c++ - 无法从 .cpp 访问 .h 中声明的私有(private)成员

C++重载

android - 在 Android 上为 OpenCV 设置相机场景模式

qt - QImage 写入时复制

qt - 在 QML 中创建一个矩形的副本

c# - 在 .NET 中将音乐从 iPad/iPhone/iPod Touch 流式传输到 PC (AirTunes)

c++ - C++中的 bool 表达式(语法)解析器