Как я могу показать модальный диалог PyQt и получить данные из своих элементов управления после его закрытия?
Для встроенного диалога, такого как QInputDialog, я прочитал, что могу это сделать:
text, ok = QtGui.QInputDialog.getText(self, 'Input Dialog', 'Enter your name:')
Как я могу эмулировать это поведение, используя диалог, который я создаю в Qt Designer? Например, я хотел бы сделать:
my_date, my_time, ok = MyCustomDateTimeDialog.get_date_time(self)
Ответы
Ответ 1
Вот простой класс, который вы можете использовать для запроса даты:
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)
и использовать его:
date, time, ok = DateDialog.getDateTime()
Ответ 2
Я попытался отредактировать ответ hluk с приведенными ниже изменениями, но он был отклонен, но не уверен, почему, поскольку он получил некоторые явные ошибки, насколько я могу см.
bugfix 1: удалено self. от self.layout.addWidget(self.buttons)
bugfix 2: подключено OK и кнопки Отмена к его правильным действиям
: сделал код готовым к запуску, включив импорт и улучшив пример выполнения
from PyQt4.QtGui import QDialog, QVBoxLayout, QDialogButtonBox, QDateTimeEdit, QApplication
from PyQt4.QtCore import Qt, QDateTime
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
self.buttons = QDialogButtonBox(
QDialogButtonBox.Ok | QDialogButtonBox.Cancel,
Qt.Horizontal, self)
layout.addWidget(self.buttons)
self.buttons.accepted.connect(self.accept)
self.buttons.rejected.connect(self.reject)
# 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)
и использовать его:
app = QApplication([])
date, time, ok = DateDialog.getDateTime()
print("{} {} {}".format(date, time, ok))
app.exec_()