這是篇翻譯的文章,翻譯的過程中自己也親自敲下代碼,更深入地瞭解QPainter的功能。
我們不論是用Qt畫圖或者是顯示文字都得用到QPainter。
QPainter
首先用QPainter來畫一條直線
import sys
from PyQt5 import QtCore, QtGui, QtWidgets, uic
from PyQt5.QtCore import Qt
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.label = QtWidgets.QLabel()
canvas = QtGui.QPixmap(400, 300)
self.label.setPixmap(canvas)
self.setCentralWidget(self.label)
self.draw_something()
def draw_something(self):
painter = QtGui.QPainter(self.label.pixmap())
painter.drawLine(10, 10, 300, 200)
painter.end()
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()
真正執行畫的操作是在do_something這個方法裏,創建個QPainter的實例,然後傳入畫布也就是QPixmap,然後執行一個畫的命令,最後用.end()來結束畫的操作。
QPainter Primitives
QPainter提供了很多畫的方法,幸運的是這些方法都是覆載過得,所以調用的時候僅有很小的差別。
例如有五種drawLine的方法,
Method | Description |
---|---|
drawLine(const QLineF &line) | Draw a QLineF instance |
drawLine(const QLine &line) | Draw a QLine instance |
drawLine(int x1, int y1, int x2, int y2) | Draw a line between x1, y2 and x2, y2 |
drawLine(const QPoint &p1, const QPoint &p2) | Draw a line between QPoint 1 and QPoint 2 |
drawLine(const QPointF &p1, const QPointF &p2) | Draw a line between QPointF 1 and QPointF 2 |