我正在尝试编写一个用户选择日期的简单代码,并使用Qlabel函数显示选择日期。但是,我在传输信号时犯了一个错误,想问一下是否有人可以帮我处理我的代码。谢谢。
from PyQt4 import QtGui, QtCore
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class MyWindow(QtGui.QWidget):
def __init__(self, parent=None):
super(MyWindow, self).__init__(parent)
self.dateEdit = QtGui.QDateEdit(self)
self.lbl = QtGui.QLabel()
self.dateEdit.setDateTime(QtCore.QDateTime.currentDateTime())
self.dateEdit.setMaximumDate(QtCore.QDate(7999, 12, 28))
self.dateEdit.setMaximumTime(QtCore.QTime(23, 59, 59))
self.dateEdit.setCalendarPopup(True)
layout = QGridLayout()
layout.addWidget(self.dateEdit,0,0)
layout.addWidget(self.lbl,0,1)
self.setLayout(layout)
self.connect(self.dateEdit, SIGNAL("dateChanged()"), self.updateUi)
def updateUi(self):
date1 = self.QtGui.QDateTimeEdit.QDate.date(self)
self.lbl.setText(date1.toString())
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
app.setApplicationName('MyWindow')
main = MyWindow()
main.show()
sys.exit(app.exec_())
答案 0 :(得分:2)
我建议使用new style signal and slots,因为它更易于阅读和阅读:
self.dateEdit.dateChanged.connect(self.onDateChanged)
信号的定义为void dateChanged (const QDate&)
,QDate
为新日期。因此,插槽应如下所示:
def onDateChanged(self,newDate):
print("The new date is "+newDate.toString())
在旁注中,您不需要使用这两个import *
(请参阅Should wildcard import be avoided?)。只需将QGridLayout()
替换为QtGui.QGridLayout()
,代码就可以在没有它们的情况下运行。
答案 1 :(得分:1)
尝试以下代码:
from PyQt4 import QtGui, QtCore
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class MyWindow(QtGui.QWidget):
def __init__(self, parent=None):
super(MyWindow, self).__init__(parent)
self.dateEdit = QtGui.QDateEdit(self)
self.lbl = QtGui.QLabel()
self.dateEdit.setDateTime(QtCore.QDateTime.currentDateTime())
self.dateEdit.setMaximumDate(QtCore.QDate(7999, 12, 28))
self.dateEdit.setMaximumTime(QtCore.QTime(23, 59, 59))
self.dateEdit.setCalendarPopup(True)
layout = QGridLayout()
layout.addWidget(self.dateEdit,0,0)
layout.addWidget(self.lbl,0,1)
self.setLayout(layout)
self.connect(self.dateEdit, SIGNAL("dateChanged(QDate)"), self.updateUi)
# or new style:
# self.dateEdit.dateChanged.connect(self.updateUi)
def updateUi(self):
date1 = self.dateEdit.date()
self.lbl.setText(date1.toString())
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
app.setApplicationName('MyWindow')
main = MyWindow()
main.show()
sys.exit(app.exec_())