凌的博客

您现在的位置是: 首页 > 学无止境 > python > 

python

33. PyQt6 绘制文本

2023-10-17 python 657
import sys
from PyQt6.QtWidgets import QApplication, QWidget
from PyQt6.QtGui import QGuiApplication, QPainter, QColor, QFont
from PyQt6.QtCore import Qt


class App(QWidget):

    def __init__(self):
        super().__init__()
        self.text = None
        self.initUI()

    def initUI(self):
        self.setWindowTitle("PyQt6 绘制文本")

        self.text = "绘制文字 \n PyQt6 Painter"

        self.setGeometry(100, 100, 400, 300)
        self.center()

    def paintEvent(self, event):
        qp = QPainter()
        qp.begin(self)
        self.drawText(event, qp)
        qp.end()

    def drawText(self, event, qp):
        qp.setPen(QColor(168, 34, 3))
        qp.setFont(QFont("Decorative", 10))
        qp.drawText(event.rect(), Qt.AlignmentFlag.AlignCenter, self.text)

    def center(self):
        qr = self.frameGeometry()
        cp = QGuiApplication.primaryScreen().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())


if __name__ == "__main__":
    app = QApplication(sys.argv)
    cls_app = App()
    cls_app.show()
    sys.exit(app.exec())

image.png

文章评论

0条评论