I want to use void * to store the pointer of the QGraphicsTextItem object created, and in another function, convert the void * pointer to a QGraphicsItem pointer for easy removal from the scene. However, I found that during the conversion, item and item2 point to different addresses; When converting QGraphicsSimpleTextItem pointers, there is no such problem. May I ask why this is happening or where I am using the problem , here is my demo:
MainWindow::MainWindow(QWidget* parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
m_pScene = new QGraphicsScene(this);
m_pView = new QGraphicsView(ui->viewWidget);
m_pView->setScene(m_pScene);
m_pView->setWindowTitle("Graphics View");
m_pView->resize(500, 500);
auto x = new QPixmap(R"(D:\desktop\Data\2D\2.bmp)");
pV = new QGraphicsPixmapItem(*x);
m_pScene->addItem(pV);
// QGraphicsTextItem
auto pTextItem = new QGraphicsTextItem("QGraphicsTextItem", pV);
auto pItem = (void*)pTextItem;
auto items = m_pScene->items();
auto item = (QGraphicsItem*)pItem;
auto b1 = items.contains(item);
auto item2 = (QGraphicsItem*)pTextItem;
auto b2 = items.contains(item2);
// QGraphicsSimpleTextItem
auto pSimpleTextItem = new QGraphicsSimpleTextItem("QGraphicsSimpleTextItem", pV);
auto pSimpleItem = (void*)pSimpleTextItem;
auto SimpleItems = m_pScene->items();
auto SimpleItem = (QGraphicsItem*)pSimpleItem;
auto b3 = SimpleItems.contains(SimpleItem);
auto Simpleitem2 = (QGraphicsItem*)pSimpleItem;
auto b4 = SimpleItems.contains(Simpleitem2);
int i = 0;
}
When you convert the void*
back to a strong pointer type, it must be the same type that you began with. But you do not do that.
Here
auto pTextItem = new QGraphicsTextItem("QGraphicsTextItem", pV);
auto pItem = (void*)pTextItem;
you convert a QGraphicsTextItem*
to void*
.
But here
auto item = (QGraphicsItem*)pItem;
you convert the void*
back to a different type. This is wrong. You must convert it back to a QGraphicsTextItem*
.
If you cannot do the back-conversion to QGraphicsTextItem*
, then you must change the forward conversion such that you first convert the QGraphicsTextItem*
to a QGraphicsItem*
and then to void*
:
auto pTextItem = new QGraphicsTextItem("QGraphicsTextItem", pV);
auto pGraphicsItem = static_cast<QGraphicsItem*>(pTextItem);
auto pItem = static_cast<void*>(pGraphicsItem);
The reason is that QGraphicsTextItem
has multiple inheritance in the class hierarchy. On the other hand, QGraphicsSimpleTextItem
only has single inheritance in the class hierarchy, which is the reason why your scheme works with the latter class.