Modal QMessageBox does not behave like native Wind

2019-07-13 12:42发布

问题:

My application has a dialog that asks the user via a QMessageBox whether he wants to discard all changes he made or wants to keep editing. I want this dialog to be modal to the whole application.

I read somewhere that this is the standard behavior for a QMessageBox, so I dont have to set it explicitly with something like:

mbox.setWindowModality(Qt::ApplicationModal);

I wonder why it behaves differently from other modal dialogs in the OS (Windows 7 in my case). On the one hand it functions like it should, i.e. all other input methods in the application are blocked until the user answeres the dialog. However, it doesn't 'blink'* if the user clicks any other window of the application. Is there any way to get Qt to behave like a native Windows dialog?

Thanks in advance!


*If you don't know what I mean with this 'blinking': Just open notepad on a Windows OS, type some text and try to close it. A dialog pops up that asks to save, discard or keep editing. Now click somewhere on the editor window -> the border and titlebar of the dialog flashes/blinks a few times.

回答1:

The problem arises when the message box has no parent. This works fine for me:

QMessageBox box(this);
box.setStandardButtons(QMessageBox::Close);
box.exec();

But this does not:

QMessageBox box;
box.setStandardButtons(QMessageBox::Close);
box.exec();

This makes sense... the message box can't blink unless it knows that its parent was clicked on.



回答2:

A simple solution that comes into my mind and if you want to deploy your application only on windows you should #include <windows.h> and use the MessageBoxA API.

Besides that this works great for me in Windows and ubuntu

if (QMessageBox::question(this,"Close?","Close this dialog?",QMessageBox::Yes,QMessageBox::No) == QMessageBox::Yes)
{
    this->close();
}