Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I show a PyQt modal dialog and get data out of its controls once its closed?

Tags:

For a built-in dialog like QInputDialog, I've read that I can do this:

text, ok = QtGui.QInputDialog.getText(self, 'Input Dialog', 'Enter your name:')

How can I emulate this behavior using a dialog that I design myself in Qt Designer? For instance, I would like to do:

my_date, my_time, ok = MyCustomDateTimeDialog.get_date_time(self)
like image 795
Thomas Johnson Avatar asked Aug 12 '13 21:08

Thomas Johnson


People also ask

How do I show dialog in Qt?

The most common way to display a modal dialog is to call its exec() function. When the user closes the dialog, exec() will provide a useful return value. Alternative way: You don't need a modal dialog. Let the dialog show modeless and connect its accepted() and rejected() signals to appropriate slots.

How to create a dialog box in PyQt5?

add the following method after the __init__ def button_clicked(self, s): print("click", s) dlg = CustomDialog() if dlg. exec(): print("Success!") else: print("Cancel!") Run it! Click to launch the dialog and you will see a dialog box with buttons.

What is QDialog in pyqt5?

A QDialog widget presents a top level window mostly used to collect response from the user. It can be configured to be Modal (where it blocks its parent window) or Modeless (the dialog window can be bypassed). PyQt API has a number of preconfigured Dialog widgets such as InputDialog, FileDialog, FontDialog, etc.


1 Answers

Here is simple class you can use to prompt for date:

class DateDialog(QDialog):
    def __init__(self, parent = None):
        super(DateDialog, self).__init__(parent)

        layout = QVBoxLayout(self)

        # nice widget for editing the date
        self.datetime = QDateTimeEdit(self)
        self.datetime.setCalendarPopup(True)
        self.datetime.setDateTime(QDateTime.currentDateTime())
        layout.addWidget(self.datetime)

        # OK and Cancel buttons
        buttons = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel,
            Qt.Horizontal, self)
        buttons.accepted.connect(self.accept)
        buttons.rejected.connect(self.reject)
        layout.addWidget(buttons)

    # get current date and time from the dialog
    def dateTime(self):
        return self.datetime.dateTime()

    # static method to create the dialog and return (date, time, accepted)
    @staticmethod
    def getDateTime(parent = None):
        dialog = DateDialog(parent)
        result = dialog.exec_()
        date = dialog.dateTime()
        return (date.date(), date.time(), result == QDialog.Accepted)

and to use it:

date, time, ok = DateDialog.getDateTime()
like image 184
hluk Avatar answered Sep 19 '22 18:09

hluk