Issue
I am trying to create a calendar that would toggle the color of a date on click. If the current background is white, set it to green. If it's green, set it to red. If it's red, set it back to white. However I do not know how to get the selection background color. Can anyone help please?
The stylesheet was set to get rid of that default selection color which blocks the color I want to show.
import sys
from PySide.QtGui import (QCalendarWidget, QApplication, QBrush)
from PySide.QtCore import Qt
class UserCalendar(QCalendarWidget):
def __init__(self, parent=None):
super(UserCalendar, self).__init__(parent)
style = 'QTableView{selection-background-color: white;' \
'selection-color: black;}'
self.setStyleSheet(style)
self.clicked.connect(self.onClick)
def onClick(self, date):
brush = QBrush()
brush.setColor(Qt.green)
charformat = self.dateTextFormat(date)
charformat.setBackground(brush)
self.setDateTextFormat(date, charformat)
style = 'QTableView{selection-background-color: green;' \
'selection-color: black;}'
self.setStyleSheet(style)
if __name__ == '__main__':
app = QApplication(sys.argv)
cal = UserCalendar()
cal.show()
cal.raise_()
sys.exit(app.exec_())
Solution
In the same way that you have set a background color with dateTextFormat(...)
you can get the color using background()
that returns the QBrush(...)
, then use its color(...) method . By default the color is black and not white as observed.
import sys
from PySide.QtGui import (QCalendarWidget, QApplication, QBrush, QColor)
from PySide.QtCore import Qt, Slot, QDate
class UserCalendar(QCalendarWidget):
def __init__(self, parent=None):
super(UserCalendar, self).__init__(parent)
self.set_selection_color(QColor("white"))
self.clicked.connect(self.onClick)
@Slot(QDate)
def onClick(self, date):
color = self.get_next_color(date)
charformat = self.dateTextFormat(date)
charformat.setBackground(QBrush(color))
self.setDateTextFormat(date, charformat)
self.set_selection_color(color)
def set_selection_color(self, color):
style = 'QTableView{{selection-background-color: {color};' \
'selection-color: black;}}'.format(color=color.name())
self.setStyleSheet(style)
def get_next_color(self, date):
color = self.dateTextFormat(date).background().color()
# by default background color is Qt.black
if color in (QColor(Qt.black), QColor(Qt.white)) :
return QColor(Qt.green)
if color == QColor(Qt.green):
return QColor(Qt.red)
return QColor(Qt.white)
if __name__ == '__main__':
app = QApplication(sys.argv)
cal = UserCalendar()
cal.show()
cal.raise_()
sys.exit(app.exec_())
Answered By - eyllanesc
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.