#include#include int main(int argc, char *argv[]) { QObject *obj = new QObject(); // do not set parent to obj QPointer ptr = obj; delete obj; if (ptr.isNull()) { qDebug() << "Object deleted!"; } else { qDebug() << "Object still exists!"; } return 0; }
#includeIn this example, a QPointer is used to handle the creation of a MyDialog object when a button is clicked. The QPointer ensures that if the parent widget is destroyed, the MyDialog is automatically set to null. Package/Library: Qt Function: QPointer Header Files: QPointer, QObject, QWidget, QPushButton, QApplication Note: The given code is limited in functionality and might require additional variable and error checking to prevent memory corruption.#include class MyWidget : public QWidget { Q_OBJECT public: MyWidget(QWidget *parent = nullptr) : QWidget(parent) { QPushButton *button = new QPushButton("Click me!", this); connect(button, &QPushButton::clicked, this, &MyWidget::handleButton); } public slots: void handleButton() { // use QPointer to ensure object still exists QPointer dlg = new MyDialog(this); dlg->exec(); } }; int main(int argc, char *argv[]) { QApplication app(argc, argv); MyWidget widget; widget.show(); return app.exec(); }