I want to have a QDialog that blocks the interaction with the MainWindow, but where initially no widget has a focus, i. e. no button has a blue border and gets pushed when hitting “Enter”.
I do not have to use a QDialog as long as I get the same behavior of blocking all interaction with the main window while the other window is open.
I tried to override the showEvent() method and invoke self.setFocus() to move the focus to the QDialog window itself, but that did not work. The focus always remained on the first button.
My idea was then to create an invisible dummy button with setDefault(True) to ensure this button receives the focus. This does not work. If I do setVisible(False) the first QPushButton in the layout gets the focus, indicated by the blue border around it. However, if I do not set visibility to false, the dummy_button is bordered blue, indicating it receives focus.
Below is my code:
import sys
from PyQt5.QtWidgets import QApplication, QDialog, QPushButton, QVBoxLayout
class CustomDialog(QDialog):
def __init__(self):
super().__init__()
self.setWindowTitle("Custom Dialog")
# Create buttons
self.button1 = QPushButton("Button 1", self)
self.button2 = QPushButton("Button 2", self)
self.button1.setDefault(False)
self.button2.setDefault(False)
self.dummy_button = QPushButton(self)
self.dummy_button.setVisible(False) # Removing this line will move the focus to the dummy button
self.dummy_button.setDefault(True)
# Layout
layout = QVBoxLayout(self)
layout.addWidget(self.button1)
layout.addWidget(self.button2)
# Set layout
self.setLayout(layout)
if __name__ == "__main__":
app = QApplication(sys.argv)
dialog = CustomDialog()
dialog.show()
sys.exit(app.exec_())