PyQt5:绘制新图纸时,保留先前绘制的图纸/线条

2024-06-11 19:50:33 发布

您现在位置:Python中文网/ 问答频道 /正文

在我画了一条新的线之后,我在维护之前绘制的线时遇到了问题。现在,如果我点击一个按钮,它会画一条线,但是一旦我点击第二个按钮,一条新的线被画出来,最初的一条就被移除了。我希望这两个都留下来。在

enter image description here

import sys
from PyQt5.QtWidgets import QMainWindow,QPushButton, QApplication
from PyQt5.QtCore import QSize, Qt, QLine, QPoint
from PyQt5.QtGui import QPainter, QPen

class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        self.setMinimumSize(QSize(300, 300)) 

        pybutton = QPushButton('button', self)
        pybutton.clicked.connect(self.draw_line)
        pybutton.resize(100,100)
        pybutton.move(0, 0) 

        pybutton2 = QPushButton('button2', self)
        pybutton2.clicked.connect(self.draw_line)
        pybutton2.resize(100,100)
        pybutton2.move(200, 0) 
        self.line = QLine()

    def draw_line(self):
        button = self.sender()
        x = int(button.x()) + int(button.width())/2
        y = int(button.y())+100
        self.line = QLine(x, y, x, y+100)
        self.update()

    def paintEvent(self,event):
        QMainWindow.paintEvent(self, event)
        if not self.line.isNull():
            painter = QPainter(self)
            pen = QPen(Qt.red, 3)
            painter.setPen(pen)
            painter.drawLine(self.line)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    mainWin = MainWindow()
    mainWin.show()
    sys.exit(app.exec_())

Tags: fromimportselfdefsyslinebuttonpyqt5
1条回答
网友
1楼 · 发布于 2024-06-11 19:50:33

短解:

QLine存储在列表中并重新绘制:

class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        self.setMinimumSize(QSize(300, 300)) 

        pybutton = QPushButton('button', self)
        pybutton.clicked.connect(self.draw_line)
        pybutton.resize(100,100)
        pybutton.move(0, 0) 

        pybutton2 = QPushButton('button2', self)
        pybutton2.clicked.connect(self.draw_line)
        pybutton2.resize(100,100)
        pybutton2.move(200, 0) 
        self.lines = []

    def draw_line(self):
        button = self.sender()
        r = button.geometry()
        p1 = QPoint(r.left() + r.width()/2, r.height())
        p2 = p1+QPoint(0, 100)
        line = QLine(p1, p2)
        if line not in self.lines:
            self.lines.append(line)
            self.update()

    def paintEvent(self,event):
        QMainWindow.paintEvent(self, event)
        painter = QPainter(self)
        pen = QPen(Qt.red, 3)
        painter.setPen(pen)
        for line in self.lines:
            painter.drawLine(line)

长期解决方案:

这类问题已经被问过无数次了,所以我要花时间来扩展,给出一个问题的总体观点,这样我就不会每次都回答这类问题了,所以这个问题 它将得到改进和更新。在

paintEvent()是一种处理Qt以执行GUI重新绘制的方法,此方法会重新绘制所有内容,因此绘图不会节省内存,因此必须存储指令并绘制图形 有了这些指示。在

我建议使用paintEvent()方法来创建自定义窗口小部件,而不是制作一个将绘制任务作为主函数执行的GUI,因为这个Qt提供了类QGraphicsViewQGraphicsScene和{}s


使用QPainter的指令重绘为drawLine()fillRect()等的任务会消耗资源,如果您想实现更高效的实现,则可以创建一个必须随时更新的QPixmap,并使用上述的QPixmap在{}中重新绘制:

^{pr2}$

相关问题 更多 >