python - PyQt5:通过单击 QPushButton 画一条线

标签 python line pyqt5 qpushbutton paintevent

我试图做到这样,当我单击 QPushButton 时,会绘制一条线。然而,我现在拥有的代码在代码启动时在开始处生成该行,而不是之后。 QPushButton 似乎没有进行任何绘图。

我也不太明白为什么在绘图时需要在函数中使用“事件”参数。

enter image description here

import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QGridLayout,QPushButton, QApplication, QWidget
from PyQt5.QtCore import QSize, QCoreApplication, Qt
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.paintEvent)
        pybutton.resize(100,100)
        pybutton.move(100, 100) 

    def paintEvent(self,event):
        print('click')
        painter = QPainter(self)
        pen = QPen(Qt.red, 3)
        painter.setPen(pen)
        painter.drawLine(0,0,100,100)

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

最佳答案

您不应该直接调用 paintEvent 方法,这应该由 Qt 处理,因为除了您想要的之外,GUI 还需要在其他情况下重新绘制它,例如当小部件调整大小、移动时,等等,接收到paintEvent的事件是一个QPaintEvent,返回一个需要重绘的矩形,这是为了优化重绘,有时很简单,因为在本例中它不是有必要使用它。

paintEvent 方法中,您必须在线不为空时绘制该线,因此您应该在连接到单击信号的插槽中执行的操作是将空线替换为有效线,并使用 update() 方法强制调用 paintEvent,通知 GUI 需要重新绘制。

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(100, 100) 
        self.line = QLine()

    def draw_line(self):
        button = self.sender()
        self.line = QLine(QPoint(), button.pos())
        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_())

关于python - PyQt5:通过单击 QPushButton 画一条线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49952610/

相关文章:

python - pip 安装要求失败

python - 将迭代器返回函数转换为 "proper iterable"返回函数的标准方法?

python - python读取大数据的不同方式

python - 从表格小部件到SQLite数据库的PYQT

python - 如何更新 Ui_MainWindow 中的 pyqt5 进度条

python - 为什么在使用 QSortFilterProxyModel 时,layoutChanged.emit() 不更新 QListView?

python - 如何为 tensorflow 构建 docker 镜像?

python - 单击Python文件时读取错误消息

list - Vim - 一次移动多行时跳回到之前的位置

awk - 使用 awk 从文件第一行打印特定字段