对于像 QInputDialog 这样的内置对话框,我读过我可以这样做:
text, ok = QtGui.QInputDialog.getText(self, 'Input Dialog', 'Enter your name:')
如何使用我在 Qt Designer 中自己设计的对话框来模拟这种行为?例如,我想做:
my_date, my_time, ok = MyCustomDateTimeDialog.get_date_time(self)
对于像 QInputDialog 这样的内置对话框,我读过我可以这样做:
text, ok = QtGui.QInputDialog.getText(self, 'Input Dialog', 'Enter your name:')
如何使用我在 Qt Designer 中自己设计的对话框来模拟这种行为?例如,我想做:
my_date, my_time, ok = MyCustomDateTimeDialog.get_date_time(self)
这是可用于提示日期的简单类:
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()
我试图用下面的更改来编辑hluk的答案,但它被拒绝了,不知道为什么,因为据我所知,它有一些明显的错误。
错误修复 1:删除了自我。来自self.layout.addWidget(self.buttons)
错误修复 2:将 OK 和 Cancel 按钮连接到正确的操作
增强:通过包含导入使代码准备好运行并改进了运行示例
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_()