如何将文本添加到 PyQt QcalendarWidget [英] How to add text to PyQt QcalendarWidget

查看:78
本文介绍了如何将文本添加到 PyQt QcalendarWidget的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何写入 QCalendarWidget 单元格?在 python 中,我不断收到画家不活跃的消息.有人可以帮我解决这个问题吗?

How does one write into the QCalendarWidget cell? In python, I keep getting painter not active message. Can someone help me out with this?

qp = QtGui.QPainter(self)
qp.setPen(QtGui.QColor(168, 34, 3))
qp.setFont(QtGui.QFont('Decorative', 10))
qp.drawText(rect, QtCore.Qt.AlignCenter, 'hello') 

rect = QtCore.QRect()
date = QtCore.QDate.fromString('2020-01-01')
calendar = QtWidgets.QCalendarWidget(self)

calendar.paintCell(qp, rect, date)

谢谢

推荐答案

您必须从 QCalendarWidget 继承并覆盖 paintCell 方法.

You must inherit from QCalendarWidget and overwrite the paintCell method.

import sys
from PyQt5.QtCore    import Qt, QRectF, QDate
from PyQt5.QtGui     import QPainter, QColor, QFont
from PyQt5.QtWidgets import QCalendarWidget, QApplication

class CalendarWidget(QCalendarWidget):

    def paintCell(self, painter, rect, date):
        painter.setRenderHint(QPainter.Antialiasing, True)
        if date == QDate(2020, 1, 1):
            painter.save()
            painter.drawRect(rect)
            painter.setPen(QColor(168, 34, 3))
            painter.setFont(QFont('Decorative', 10))            
            painter.drawText(QRectF(rect), Qt.TextSingleLine|Qt.AlignCenter, str(date.day()))
            painter.drawText(rect, Qt.AlignCenter, 'Hello\nWorld') 

            painter.restore()
        else:
            QCalendarWidget.paintCell(self, painter, rect, date)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = CalendarWidget()
    w.show()
    sys.exit(app.exec_())

这篇关于如何将文本添加到 PyQt QcalendarWidget的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆