2 回答

TA貢獻1993條經驗 獲得超6個贊
您可以在方法內繪制線條,paintEvent()而不是直接在圖像上繪制,然后在實際釋放鼠標時在圖像上繪制。
class DrawingArea(QWidget):
def __init__(self, parent=None):
super(DrawingArea, self).__init__(parent)
self.setAttribute(Qt.WA_StaticContents)
self.scribbling = False
self.myPenWidth = 1
self.myPenColor = QColor('#000000')
self.image = QImage()
self.startPoint = self.endPoint = None
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.startPoint = event.pos()
def mouseMoveEvent(self, event):
if self.startPoint:
self.endPoint = event.pos()
self.update()
def mouseReleaseEvent(self, event):
if self.startPoint and self.endPoint:
self.updateImage()
def paintEvent(self, event):
painter = QPainter(self)
dirtyRect = event.rect()
painter.drawImage(dirtyRect, self.image, dirtyRect)
if self.startPoint and self.endPoint:
painter.drawLine(self.startPoint, self.endPoint)
def updateImage(self):
if self.startPoint and self.endPoint:
painter = QPainter(self.image)
painter.setPen(QPen(self.myPenColor, self.myPenWidth, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
painter.drawLine(self.startPoint, self.endPoint)
painter.end()
self.startPoint = self.endPoint = None
self.update()
請注意,您不需要update()在調整大小事件中調用,因為它是自動調用的。
我還刪除了不必要的更新矩形調用,因為在這種情況下它幾乎沒有用:指定一個應該發生更新的矩形通常是在繪制非常復雜的小部件時完成的(特別是當執行大量計算以正確繪制所有內容并且僅繪制一個小部件的一小部分實際上需要更新)。在您的情況下,計算實際更新矩形幾乎比繪制小部件的所有內容更耗時。

TA貢獻1836條經驗 獲得超3個贊
例如,它展示了如何實現一個自定義類,它實際上為您提供了一個“繪圖板”:
class Canvas(QLabel):
? ? def __init__(self):
? ? ? ? super().__init__()
? ? ? ? pixmap = QtGui.QPixmap(600, 300)
? ? ? ? self.setPixmap(pixmap)
? ? ? ? self.last_x, self.last_y = None, None
? ? ? ? self.pen_color = QtGui.QColor('#000000')
? ? def set_pen_color(self, c):
? ? ? ? self.pen_color = QtGui.QColor(c)
? ? def mouseMoveEvent(self, e):
? ? ? ? if self.last_x is None:? # First event.
? ? ? ? ? ? self.last_x = e.x()
? ? ? ? ? ? self.last_y = e.y()
? ? ? ? ? ? return? # Ignore the first time.
? ? ? ? painter = QtGui.QPainter(self.pixmap())
? ? ? ? p = painter.pen()
? ? ? ? p.setWidth(1)
? ? ? ? p.setColor(self.pen_color)
? ? ? ? painter.setPen(p)
? ? ? ? painter.drawLine(self.last_x, self.last_y, e.x(), e.y())
? ? ? ? painter.end()
? ? ? ? self.update()
? ? ? ? # Update the origin for next time.
? ? ? ? self.last_x = e.x()
? ? ? ? self.last_y = e.y()
? ? def mouseReleaseEvent(self, e):
? ? ? ? self.last_x = None
? ? ? ? self.last_y = None
您可以在任何需要的地方使用這個 Canvas 類(或者您給它起的任何名稱)。例如在主窗口中:
class MainWindow(QMainWindow):
? ? def __init__(self, parent=None):
? ? ? ? QMainWindow.__init__(self, parent)
? ? ? ? self.canvas = Canvas()
? ? ? ? self.canvas.set_pen_color('#fffee5')? # set the colour you want
? ? ? ? self.setCentralWidget(self.canvas)
? ? ? ? self.show()
希望這能有所幫助!快樂編碼!:)
添加回答
舉報