user3135832
user3135832

Reputation: 211

How to create a modal window in pyqt?

I looked into the documentation and I found self.setWindowModality(QtCore.Qt.WindowModal).

I added this function to my __init__ function, but however still was not able to create a modal dialog box.

Any help will be appreciated,
Thank You.

Upvotes: 16

Views: 40368

Answers (2)

Matthew Bendyna
Matthew Bendyna

Reputation: 1

You should use the setWindowModal(2) method from your QWidget object

from PyQt5 import QtGui, QtWidgets, QtCore
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow
import sys

class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setGeometry(400, 400, 500, 500)
        self.setWindowTitle("Multi Window Application")
        self.initUI()
    def initUI(self):
        self.child_access = QtWidgets.QPushButton(self)
        self.child_access.setText("Child 1")
        self.child_access.adjustSize()
        self.child_access.move(100, 100)
        self.child_access.clicked.connect(self.openChild1)
    def openChild1(self):
        self.child1 = Child1()
        self.child1.setWindowModality(2)
        self.child1.show()

class Child1(QWidget):
    def __init__(self):
        super().__init__()
        self.setGeometry(200, 200, 300, 300)
        self.setWindowTitle("Child 1")
        self.initUI()
    def initUI(self):
        self.label = QtWidgets.QLabel(self)
        self.label.setText("Child1")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = MainWindow()
    win.show()
    app.exec_()
    sys.exit()

Upvotes: 0

Shadow9043
Shadow9043

Reputation: 2260

QDialog has setModal() as found here.

As the docs state:

By default, this property is False and show() pops up the dialog as modeless. Setting this property to true is equivalent to setting QWidget.windowModality to Qt.ApplicationModal.

As @sebastian noted you could use exec(). However it is better to use exec_() as the one sebastian mentioned is also a python call.

Example:

my_dialog = QDialog(self) 
my_dialog.exec_()  # blocks all other windows until this window is closed.

If this doesn't help please post your code and I will have a look.

Upvotes: 32

Related Questions