2021/October 2021

PyQT5 simple, self-contained snippet for dialog popup

hajinny 2021. 10. 6. 18:44

It seems like I need to just make a pop up from time to time, and it's annoying because all the sample codes out there are not self-contained, so it's really annoying to piece things together. Here's the boilerplate that will pop a dialog up when that hello button is pressed

 

class InvitationAcceptDeclineDialog(QDialog):
    def __init__(self, parent):
        super().__init__(parent)
        self.initUI()

    def initUI(self):
        vbox = QVBoxLayout()
        vbox.addWidget(QLabel("You are invited"))

        hbox = QHBoxLayout()
        btn_accept = QPushButton("Invite")
        
        btn_decline = QPushButton("Cancel")
        hbox.addWidget(btn_accept)
        hbox.addWidget(btn_decline)

        vbox.addLayout(hbox)
        
        self.setLayout(vbox)
        self.setWindowTitle('Connection Page')
        self.setGeometry(300, 300, 200, 200)

class Sample(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        hbox = QHBoxLayout()
        popDialog = QPushButton("hello")
        hbox.addWidget(popDialog)

        def showDialog():
            invite=InvitationAcceptDeclineDialog(self)
            invite.show()

        popDialog.clicked.connect(showDialog)

        self.setLayout(hbox)
        self.setWindowTitle('Connection Page')
        self.setGeometry(300, 300, 500, 500)
        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    hi = Sample()
    sys.exit(app.exec_())