📅  最后修改于: 2023-12-03 15:18:48.126000             🧑  作者: Mango
QCalendarWidget
is a commonly used GUI widget in PyQt5 to handle dates in a graphical format. In this article, we will discuss how to set the change event for the QCalendarWidget
.
To set the change event for QCalendarWidget
, we need to use the clicked
signal. This signal is emitted whenever a new date is selected in the calendar.
from PyQt5.QtWidgets import QApplication, QCalendarWidget, QWidget
class App(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
cal = QCalendarWidget(self)
cal.setGeometry(10, 10, 250, 200)
cal.clicked[QDate].connect(self.onDateSelected)
# set the clicked signal here
self.setGeometry(300, 300, 300, 250)
self.setWindowTitle('QCalendarWidget')
self.show()
def onDateSelected(self, date):
print(date.toString())
if __name__ == '__main__':
app = QApplication([])
ex = App()
app.exec_()
In the initUI
function, we first create a QCalendarWidget
object and set its size and position on the window. Then, we use clicked[QDate]
signal and connect it to the onDateSelected
function.
Finally, we implement the onDateSelected
function. This function takes a date object and prints it to the console.
Now, when you run the program, select a date on the QCalendarWidget
and watch as the onDateSelected
method is called, printing the selected date to the console.
In this article, we have discussed how to set the change event for QCalendarWidget
in PyQt5. By using the clicked
signal, we connected the signal to the onDateSelected
function and printed the selected date to the console.