PyQt5 QCalendarWidget - Setting Background Color

PyQt5 QCalendarWidget - Setting Background Color

Setting the background color of a QCalendarWidget in PyQt5 can be done using style sheets, which is a powerful way to style widgets in PyQt. Here's how you can set the background color of a QCalendarWidget:

Step 1: Import PyQt5 Modules

First, import the necessary PyQt5 modules:

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

Step 2: Create a Main Window

Create a main window class that will hold the calendar widget:

class MainWindow(QMainWindow): def __init__(self): super().__init__() # Create Calendar Widget self.calendar = QCalendarWidget(self) self.setCentralWidget(self.calendar) # Set Background Color using Style Sheet self.calendar.setStyleSheet("background-color: lightblue;") # Set your desired color # Adjust size and position self.calendar.setFixedSize(400, 300) self.setGeometry(100, 100, 400, 300) 

Step 3: Run the Application

Finally, create an instance of QApplication and your main window, and then start the event loop:

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

Complete Code

Here's the complete code put together:

from PyQt5 import QtWidgets from PyQt5.QtWidgets import QApplication, QMainWindow, QCalendarWidget import sys class MainWindow(QMainWindow): def __init__(self): super().__init__() self.calendar = QCalendarWidget(self) self.setCentralWidget(self.calendar) self.calendar.setStyleSheet("background-color: lightblue;") # Set your desired color self.calendar.setFixedSize(400, 300) self.setGeometry(100, 100, 400, 300) app = QApplication(sys.argv) mainWin = MainWindow() mainWin.show() sys.exit(app.exec_()) 

Notes

  • Style Sheets: You can customize not just the background color but also other aspects like text color, border, etc., using the style sheet.
  • Color Formats: You can specify the color in various formats like lightblue, #RRGGBB, rgb(173, 216, 230), etc.
  • Widget Size and Position: Adjust the size and position of the calendar widget as per your requirement.

This example demonstrates how to change the background color of a QCalendarWidget in PyQt5. You can modify the style sheet to further customize the appearance of the calendar.


More Tags

text-widget runnable datacontext mockito wcf xamarin.ios parameter-passing webpack-4 cxf message-queue

More Programming Guides

Other Guides

More Programming Examples