我想将p.drawText (r.x () + 10, r.y () + 33, '{} / {}'. Format ('tset1', 'test2')条件的文本放在所选的QCalendarWidget日期上。但这不好。

import sys
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *

class main_window(QWidget):
    def __init__(self):
        super(main_window, self).__init__()
        self.resize(1280, 900)

        self.Calendar()

    def Calendar(self):
        self.cal = QCalendarWidget(self)
        self.cal.resize(500, 500)
        self.cal.clicked.connect(self.Calendar_click)

    def Calendar_click(self):
        p = QPainter()
        r = QRect(0,0,10,10)
        d = self.cal.selectedDate()
        self.cal.paintCell(p, r, d)
        if (d == QDate.currentDate()):
            f = QFont()
            f.setPixelSize(10)
            f.setBold(True)
            f.setItalic(True)
            p.setFont(f)
            p.drawText(r.x()+10, r.y()+33, '{}/{}'.format('tset1','test2'))

if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = main_window()
    main.show()


我已经尝试了很多,但是我仍然不知道如何在所选日期添加小文本。

最佳答案

您必须覆盖paintCell()方法,因为此方法在paintEvent()中被调用:

class CalendarWidget(QCalendarWidget):
    def paintCell(self, painter, rect, date):
        super(CalendarWidget, self).paintCell(painter, rect, date)
        if date == self.selectedDate():
            painter.save()
            f = QFont()
            f.setPixelSize(10)
            f.setBold(True)
            f.setItalic(True)
            painter.setFont(f)
            r = rect
            painter.drawText(
                rect.topLeft() + QPoint(10, 33),
                "{}/{}".format("tset1", "test2"),
            )
            painter.restore()


class main_window(QWidget):
    def __init__(self):
        super(main_window, self).__init__()
        self.resize(1280, 900)
        self.Calendar()

    def Calendar(self):
        self.cal = CalendarWidget(self)
        self.cal.resize(500, 500)




更新:

如果要保留文本,则必须保存日期并根据需要重新绘制,因为Qt会重新绘制所有内容

class CalendarWidget(QCalendarWidget):
    def __init__(self, parent=None):
        super(CalendarWidget, self).__init__(parent)
        self._selected_dates = set()
        self._selected_dates.add(self.selectedDate())
        self.clicked.connect(self.on_clicked)

    @pyqtSlot(QDate)
    def on_clicked(self, date):
        self._selected_dates.add(date)

    def paintCell(self, painter, rect, date):
        super(CalendarWidget, self).paintCell(painter, rect, date)
        if date in self._selected_dates:
            painter.save()
            f = QFont()
            f.setPixelSize(10)
            f.setBold(True)
            f.setItalic(True)
            painter.setFont(f)
            r = rect
            painter.drawText(
                rect.topLeft() + QPoint(10, 33),
                "{}/{}".format("tset1", "test2"),
            )
            painter.restore()

关于python - 我想将文字放在pyqt QCalendarWidget中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55673665/

10-11 03:54