I am trying to replicate behaviour in a small PyQt application, but instead using C++.
The reason for this is purely education and I am not interested in answering stating to change the behaviour. I have a bug in a much larger codebase that when using PyQt and I delete the parent of a modal dialog, the window position changes.
I am trying to create the following scenario using Qt.
I have a Main application dialog, which is a parent of a dialog I called ABParent. ABParent is a dialog which is a parent of Dialogs A and B. A, B and ABParent are all modal. When dialog B appears, I want to do the following,
- Call
deleteLater
on DialogB - Call
deleteLater
on the modal parentABParent
- Call
deleteLater
on Dialog C.
This replicates the code behaviour to which I observe the main window positioning change. However, unlike when doing this in Python, the application crashes with (process 34820) exited with code -1073740940.
MY C++ code is,
#include <QApplication>
#include <QDialog>
#include <QLabel>
#include <QPushButton>
#include <QVBoxLayout>
#include <iostream>
#include "main.h"
#include "moc_main.cpp" // Ensure the moc file is included
DialogB::DialogB(QWidget *parent) : QDialog(parent)
{
setWindowTitle("Dialog B");
setLayout(new QVBoxLayout());
QPushButton *closeButton = new QPushButton("Close", this);
layout()->addWidget(closeButton);
setWindowModality(Qt::ApplicationModal);
connect(closeButton, &QPushButton::clicked, this, &DialogB::close_dialog);
}
void DialogB::close_dialog()
{
std::cout << "Deleting B" << std::endl;
deleteLater(); // Delete B
ABParent *parentDialog = qobject_cast<ABParent *>(parent());
if (parentDialog) {
std::cout << "Deleting parent " << parentDialog->objectName().toStdString() << std::endl;
parentDialog->deleteLater(); // Delete the Modal parent
std::cout << "Deleting A" << std::endl;
parentDialog->dialogA->deleteLater(); // Delete dialog A
}
}
ABParent::ABParent(QWidget *parent) : QDialog(parent)
{
setWindowTitle("AB Parent");
setObjectName("AB Parent");
setWindowModality(Qt::ApplicationModal);
dialogA = new QDialog(this);
dialogB = new DialogB(this);
dialogA->setWindowTitle("Dialog A");
dialogA->setWindowModality(Qt::ApplicationModal);
dialogA->show();
dialogB->show();
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QDialog mainwindow;
mainwindow.setWindowTitle("Main Window");
mainwindow.show();
ABParent abparent = ABParent(&mainwindow);
abparent.show();
return app.exec();
}
and the header file,
#pragma once
#include <QDialog>
class DialogB;
class ABParent : public QDialog {
Q_OBJECT
public:
QDialog *dialogA;
DialogB *dialogB;
ABParent(QWidget *parent = nullptr);
};
class DialogB : public QDialog {
Q_OBJECT
public:
DialogB(QWidget *parent = nullptr);
public slots:
void close_dialog();
};
Would anybody be able to help me understand why the application is crashing? When I have the equivalent in PyQt6 code, it does not.