【问题标题】:How to add text to PyQt QcalendarWidget [duplicate]如何将文本添加到 PyQt QcalendarWidget [重复]
【发布时间】:2020-06-25 00:35:46
【问题描述】:

如何写入 QCalendarWidget 单元格?在 python 中,我不断收到painter not active 消息。有人可以帮我解决这个问题吗?

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)

谢谢

【问题讨论】:

    标签: pyqt5 qpainter qcalendarwidget


    【解决方案1】:

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

    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_())
    

    【讨论】:

    • 非常好!但是我已经将日历作为 MainWindow 的一部分(不是弹出窗口),并在我运行应用程序时对其进行初始化。我需要读取它并写入它——我还能在上面画画吗?
    • 好的,我明白了。按照建议创建了一个类,将其附加到选项卡上,作为self.calendar_2 = CalendarWidget(self.ui.tab_2) ,现在,我如何将参数传递给它,特别是日期和文本?有什么办法吗?
    • 好的,我也想通了。现在的问题是,我如何将当天的数字保存在该单元格中。它似乎被文本覆盖了。
    • 好的,现在知道了。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-27
    • 2022-12-11
    相关资源
    最近更新 更多