c++ - QT 图形 View 在场景中查找项目

标签 c++ qt qgraphicsview

我使用图形 View 框架创建了一个图形场景。 我有几个 (7 - 10) 椭圆(垂直放置)创建的:

ellipse = scene->addEllipse(x1, y1, w, h, pen, brush);

现在我想为动画准备图形。首先所有的椭圆都是黑色的。 5 秒后,第一个应为红色,5 秒后第一个 = 绿色,第二个 = 红色,依此类推。

我的想法是获取第一项并为椭圆着色。但是我怎样才能得到椭圆项目呢?有这样的功能吗?

最佳答案

您可以使用 items() 方法获取所有元素的排序列表。 然后遍历列表,检查是否为椭圆项。

对于更多特殊情况,Item 也会重载,看看其中是否符合您的需求。

方法:

QList<QGraphicsItem *> QGraphicsScene::items() const

您可以在此处找到文档:http://doc.qt.io/qt-4.8/qgraphicsscene.html#items

如果您有性能问题,这里是 Qt 文档的摘录,我 100% 同意:

One of QGraphicsScene's greatest strengths is its ability to efficiently determine the location of items. Even with millions of items on the scene, the items() functions can determine the location of an item within few milliseconds. There are several overloads to items(): one that finds items at a certain position, one that finds items inside or intersecting with a polygon or a rectangle, and more. The list of returned items is sorted by stacking order, with the topmost item being the first item in the list. For convenience, there is also an itemAt() function that returns the topmost item at a given position.


检查您可以使用的项目类型:

int QGraphicsItem::type() const

摘自 docs :

Returns the type of an item as an int. All standard graphicsitem classes are associated with a unique value; see QGraphicsItem::Type. This type information is used by qgraphicsitem_cast() to distinguish between types.

第二种方法是直接使用qgraphicsitem_cast()

这是一个 Example使用自定义 GraphicsItem Node:

// Sum up all forces pushing this item away
qreal xvel = 0;
qreal yvel = 0;
foreach (QGraphicsItem *item, scene()->items()) {
    Node *node = qgraphicsitem_cast<Node *>(item);
    if (!node)
        continue;

    QPointF vec = mapToItem(node, 0, 0);
    qreal dx = vec.x();
    qreal dy = vec.y();
    double l = 2.0 * (dx * dx + dy * dy);
    if (l > 0) {
        xvel += (dx * 150.0) / l;
        yvel += (dy * 150.0) / l;
    }
}

关于c++ - QT 图形 View 在场景中查找项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30191586/

相关文章:

qt4 - 单个 QGraphicsScene 的多个 QGraphicsView

c++ - 在 C++ 中将实际数据和调试数据流式传输到磁盘

c++ - 尝试在代码块中编译 Qt/C++ 代码

c++ - QComboBox 放置位置正在移动

c++ - 将自己的对象放入 QGraphicsScene

python - 主窗口中的多个 QGraphicsView 和 QGraphicsScene

C++练习煎饼

c++ - deque::shrink_to_fit内存保证

c++ - 从指针中提取 2 个字节 (u_short)

c++ - Qt 回调列表