Centering a QMessageBox relative to the main window?
In my program I have several C++ classes that are Qt-based (that is, they use QObjects instead of generic C++ objects) but lack user interfaces of their own. I use QMessageBoxes in the error handling code in these classes to alert users if an error occurs.
When I'm working with these classes, I can't use this as a parent since there is no interface to center the message box against. The only way I can get the code to compile in such instances is to use NULL as a parent but that causes the message boxes to be centered on the screen instead of relative to the main window. It works but it looks really strange if the main window isn't positioned close to the center of the screen.
Is there a way to force these message boxes to center relative to the app's main window? The most logical way to fix this problem would be to create a pointer to the active mainwindow object to use as a parent but I'm not quite sure how to do it. Any suggestions?
What about "this":http://qt-project.org/doc/qt-4.8/qapplication.html#activeWindow ?
Didn't work. I just tried
m.critical(mw, "blah", "blah blah");@
and the message boxes are still centering on the screen. It looks like that method requires the main window to have focus at the time, so maybe it's not working for me because a QDialog initiates this code.
QMainWindow --> QDialog --> Another class that contains this code
QMainWindow --> Another class that contains this code
Since that QDialog is destroyed by the time this code is executed, it looks like QApplication::activeWindow() is returning nothing (unless the focus automatically returns to the main window once the QDialog is gone).
I also unsuccessfully tried mw->parentWidget() to see if mw was pointing to the QDialog. It compiles but the app crashes when the program flow gets to that point (that pointer must be null if mw is returning 0).
if you use QMessageBox' static methods to display it you wont be able to access them. Since you wont get a pointer to work with the respecting widget.
@raven-worx: I don't understand. Are you saying there is no way to create a pointer to the active QMainWindow object?
raven-worx just said that you are using critical the wrong way, it's a static function
A static object was indeed the right way to do this. I solved this problem by creating a public static pointer to the main window object in the MainWindow class:
@ static QWidget* mw;@
and setting the pointer to
in the main window constructor. By including MainWindow in all classes that need this type of parent, I can now properly center dialogs in classes without UIs by using MainWindow::mw as the parent.
Thanks for the help!
QApplication::topLevelWidgets() might be cleaner