htmlamateur htmlamateur - 3 months ago 20
C++ Question

How to close only subwindow when use closeEvent for X button?

I use method

closeEvent
for X button on the top right in the interface.

window

The requirements are:


  • when I click "Close" -> both windows (Exit and MainWindow) will be closed.

  • when I click "Cancel"-> only "Exit" windows will be closed, MainWindow still stays there.



But when I click on "Cancel", both windows are closed -> how to solve this problem?

How to move button "Cancel" in between "Save" and "Close"

dialog

This is my code

myclass.h

class MyClass : public QWidget
{
Q_OBJECT

public:
MyClass(QcgDatabase* db, int hostid, QWidget *parent = 0);
~MyClass();

public slots:
void save_clicked();

private:
Ui::MyClass ui;
QMessageBox* dialog = NULL;
void closeEvent(QCloseEvent *bar);
};


myclass.cpp

MyClass::MyClass(QcgDatabase * db, int hostid, QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
.......
.......
}

void MyClass::closeEvent(QCloseEvent *bar)
{
if (!dialog) {
dialog = new QMessageBox(this);
}
dialog->setWindowModality(Qt::WindowModal);
dialog->setWindowTitle(QLatin1String("Exit"));
dialog->setText(QLatin1String("You have not saved data. Click \"Close\" to close the data table."));
dialog->setStandardButtons(QMessageBox::Save | QMessageBox::Cancel | QMessageBox::Close);

int result = dialog->exec();
if (result == QMessageBox::Save) {
save_clicked();
}
else if (result == QMessageBox::Cancel) {
dialog->close();
return;
}
else if (result == QMessageBox::Close) {
dialog->close();
}

bar->accept();
}


Edit:

ok, i fixed the problem with window:

else if (result == QMessageBox::Cancel) {
bar->ignore();
return;
}


Please help me to swap position of buttons "Close" and "Cancel"!

Answer

In your if (result == QMessageBox::Cancel) branch it is not enough to close only your dialog. You also need to call QEvent::ignore() on the event object:

bar->ignore()

This is because your MyClass::closeEvent is called only to give you chance to do something when window is about to be closed, but event itself will continue its journey in the labyrinth of Qt framework and eventualy will cause window to be closed - unless you mark it to be ignored

Comments