Tho*_*son 16 python qt dialog modal-dialog pyqt
对于像QInputDialog这样的内置对话框,我读过我可以这样做:
text, ok = QtGui.QInputDialog.getText(self, 'Input Dialog', 'Enter your name:')
Run Code Online (Sandbox Code Playgroud)
如何使用我在Qt Designer中设计自己的对话框来模拟此行为?例如,我想这样做:
my_date, my_time, ok = MyCustomDateTimeDialog.get_date_time(self)
Run Code Online (Sandbox Code Playgroud)
hlu*_*luk 30
这是一个简单的类,可用于提示日期:
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)
Run Code Online (Sandbox Code Playgroud)
并使用它:
date, time, ok = DateDialog.getDateTime()
Run Code Online (Sandbox Code Playgroud)
lou*_*lou 27
我尝试使用下面的更改编辑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)
Run Code Online (Sandbox Code Playgroud)
并使用它:
app = QApplication([])
date, time, ok = DateDialog.getDateTime()
print("{} {} {}".format(date, time, ok))
app.exec_()
Run Code Online (Sandbox Code Playgroud)