QMainWindow does not regain focus after QDialog is closed

As a follow-up for this question:

I have a QMainWindow that opens a QDialog. When the QDialog is closed the focus is "lost" - the QMainWindow doesn't get it back and no other widget seems to have it (actually, there are no active widgets besides those two). How can I enforce the regaining of the focus by QMainWindow? Currently I'm doing this in the eventFilter of my QMainWIndow:

if(!hasFocus()) { 
    setFocus();
}

But, I'm afraid that this fix is wrong and might cause bugs that I can't even imagine right now...

Update + code:

My QMainWindow has an event filter installed. It holds a QWidget object whose parent is the QMainWindow. The constructor of the widget:

MyWidget::MyWidget(QWidget *parent) :
 QWidget(parent) {
 ui.setupUi(this);
 installEventFilter(parent);
 // do something here
}

The QWidget object has a slot that creates a dialog and calls it's exec function:

void MyWidget::openDialog() {
 MyDialog dialog(num);
 if (!dialog.exec()) {
   return;
 }
 setNum(dialog.getNum());
}

As you can see, the dialog has no parent set - this was the case in the beginning. I tried to change it, but neither

MyDialog dialog(num, this);

nor

MyDialog dialog(num, parentWidget());

worked.

Solution:

Apparently, a tiny button was stealing the focus after dialog's closure. The button was located in a widget placed on the main window. It's a very nasty bug that took me a lot of time and effort to find.

链接地址: http://www.djcxy.com/p/6686.html

上一篇: 按下按钮后如何将焦点设置到游戏区域

下一篇: QDialog关闭后,QMainWindow不会重新获得焦点