gpt4 book ai didi

C++如何枚举QGraphicsItem?

转载 作者:行者123 更新时间:2023-11-28 02:35:17 24 4
gpt4 key购买 nike

使用此函数,我可以从 QGraphicsView 中删除选定的 QGraphicsItem。我怎样才能枚举我的省略号,以便收到像 "Deleted ellipse n°..." 这样的通知。

void MainWindow::deleteItem()
{
foreach (QGraphicsItem *item, scene->selectedItems()) {
if (item->type() == ellipse->Type) {
scene->removeItem(item);
delete item;
QMessageBox::information(this,"Notification", "Deleted");
}
}

}

最佳答案

几种方式

假设您只关心该迭代:

   int ix = 0; // add this
foreach (QGraphicsItem *item, scene->selectedItems()) {
if (item->type() == ellipse->Type) {
scene->removeItem(item);
delete item;
std::cout << "Deleted ellipse number " << ix++ << std::endl; // and add this
QMessageBox::information(this,"Notification", "Deleted");
}
}

以上仅在您的排序仅对应于该 foreach() 循环时才有效。如果您的项目是任意顺序的:

std::unordered_map<QGraphicsItem*, int> mGraphicsItems;

当然,这是假设您可以填充它。如果可以,请在调用 delete() 之前进行查找,以获取作为枚举的值。虽然不是很优雅,但增加了空间。

其他方法是子类化 QGraphicsItem [未经测试的代码,但你明白了]

class MyGraphicsItem : public QGraphicsItem
{
Q_OBJECT
public:
// snip
int index() const { return mIndex; }
void setIndex( int i ) { mIndex = i; }
private:
int mIndex;
};

只需在创建 QGraphicsItem 时以任何您想要的方式设置索引,然后在调用 delete 之前,使用 item->index() 打印(或执行任何操作);

关于C++如何枚举QGraphicsItem?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27695053/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com