python - 使用 QPainter 更改线条的位置

标签 python qt pyqt4 qpainter qtgui

我有一个带有按钮的窗口。单击按钮后,我想更改最初绘制的线条的位置。到目前为止,这是我的代码。

import sys 
from PyQt4 import QtGui , QtCore

class trial(QtGui.QWidget):
    def __init__(self):
        super(trial , self).__init__()
        self.window()

    def window(self):
        self.a = 0
        button = QtGui.QPushButton('Push')
        button.setCheckable(True)
        button.clicked.connect(self.fun)
        grid = QtGui.QGridLayout()
        grid.addWidget(button , 0 , 0)
        self.setLayout(grid)
        self.setWindowTitle('Trial')
        self.setGeometry(500 , 500 , 500 , 500)
        self.show()

    def fun(self , text):
        if text == 1:
            self.a = 0

        else:
            self.a = 1


    def paintEvent(self , e):
        qp = QtGui.QPainter()
        qp.begin(self)
        pen = QtGui.QPen(QtCore.Qt.red , 5 , QtCore.Qt.SolidLine)
        qp.setPen(pen)

        if self.a == 0:

            qp.drawLine(20 , 20 , 20 , 480)
        else:
            qp.drawLine(480 , 20 , 480 , 480) 
        qp.end()


if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    t = trial()
    sys.exit(app.exec_())

我知道我的代码看起来有点尴尬,但我面临以下问题。 1. 按下按钮后,线需要相当长的时间才能改变位置。

2.另外如何擦掉之前画的线。

如果有人可以帮我修改代码,那就太好了。谢谢。

最佳答案

1) 在您的 fun() 函数中添加对 self.update() 的调用,让 Qt 知道您的小部件需要重新绘制

2) (不太确定 python 语法,所以我将用 C++ 给出示例)

您可以在绘制事件中显式绘制背景:

qp.setBrush( Qt::white );  // Or whatever color you want the background to be 
qp.drawRect( rect() );

或者你可以尝试搞乱 QWidget::setAutoFillBackground()

关于python - 使用 QPainter 更改线条的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13380003/

相关文章:

python-2.7 - 在 QTableWidget 中使用 setCellWidget 对列进行排序

python - 如何使用pyqt4在窗口中的网页上建立链接?

python - 从 Ruby 到 Python - 是否有 "try"的等价物?

python - Keras 中的矩阵乘法

css - Qt 4.8.5 嵌入式 : QToolButton text align

c++ - Qt 中可调整大小和最大化的窗口

python - PyQt Webkit 和 html 表单 : Fetching output and closing window

python - 使用 SQL SELECT 语句将 SQLite 数据库转换为 Python 字典

python - 有条件地将 pandas.DataFrame 中的值替换为之前的值

c++ - 使用带有接口(interface)和新语法的 Qt 连接时出错