📜  PyQt5 QCalendarWidget – 设置动作事件(1)

📅  最后修改于: 2023-12-03 15:18:48.081000             🧑  作者: Mango

PyQt5 QCalendarWidget – Setting Action Events

The QCalendarWidget class in PyQt5 provides a user-friendly calendar widget for selecting dates. It allows the programmer to set action events to be triggered when certain events occur, providing a way to customize the behavior of the calendar widget.

To set action events in QCalendarWidget, we can follow these steps:

Step 1: Creating a QCalendarWidget

First, we need to create an instance of the QCalendarWidget class. Here is an example of how to create a basic calendar widget:

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QCalendarWidget

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        
        self.calendar = QCalendarWidget(self)
        self.setCentralWidget(self.calendar)

app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())

In the above example, we create a simple MainWindow class that inherits from QMainWindow. We create an instance of QCalendarWidget and set it as the central widget of the main window.

Step 2: Setting Action Events

To set action events in the QCalendarWidget, we can use the clicked signal. This signal is emitted when the user clicks on a day in the calendar. We can connect this signal to a custom slot to perform some action when the event occurs.

Here is an example of how to set an action event to display the selected date in the console:

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QCalendarWidget

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.calendar = QCalendarWidget(self)
        self.calendar.clicked.connect(self.on_date_selected)

        self.setCentralWidget(self.calendar)

    def on_date_selected(self, date):
        print(date.toString("yyyy-MM-dd"))

app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())

In the above example, we connect the clicked signal of the calendar widget to the on_date_selected slot. The on_date_selected method takes the selected date as an argument and displays it in the console using the toString method.

By customizing the on_date_selected method, programmers can perform various actions based on the selected date, such as updating a database, displaying related information, or triggering other events.

Conclusion

The QCalendarWidget class in PyQt5 provides an easy way to select dates, and by setting action events, programmers can customize the behavior of the calendar widget. By connecting the clicked signal to a custom slot, programmers can perform specific actions based on the selected date.