简体   繁体   English

如何在pyqt5 paintEvent中添加参数?

[英]How to add an argument to pyqt5 paintEvent?

A function that runs inside of paintEvent needs a multiprocessing.Queue object to be passed into itself. 在paintEvent中运行的函数需要将multiprocessing.Queue对象传递给自身。

I have tried to use global python lists but lists don't work with the multiprocessing library. 我曾尝试使用全局python列表,但列表不适用于多处理库。 In the "main" section of my code I create a multiprocess.Queue object. 在我的代码的“main”部分,我创建了一个multiprocess.Queue对象。 The function drawMandelbrot is part of my QWidget class and is executed by the paintEvent. 函数drawMandelbrot是我的QWidget类的一部分,由paintEvent执行。 The paint event runs whenever the gui window needs to be drawn on the screen. 只要需要在屏幕上绘制gui窗口,就会运行paint事件。 But the function drawMandelbrot needs to access the Queue object to get data that needs to be drawn. 但是函数drawMandelbrot需要访问Queue对象以获取需要绘制的数据。

if __name__ == '__main__':
    procQueue = Queue()
    app = QApplication([])
    #Called whenever the window is resized or brought into focus
    def paintEvent(self, event, procQueue):
        qp = QPainter()
        qp.begin(self)

        #Run the drawMandelbrot program
        self.drawMandelbrot(qp, procQueue)
        qp.end()

I expect the function to pass the Queue object into the drawMandelbrot function. 我希望函数将Queue对象传递给drawMandelbrot函数。 When the program is run it gives the error "TypeError: paintEvent() missing 1 required positional argument: 'Queue'". 当程序运行时,它会给出错误“TypeError:paintEvent()缺少1个必需的位置参数:'Queue'”。 How do I allow the drawMandelbrot function to have access to the Queue object that I created in my "main" section of the python app? 如何允许drawMandelbrot函数访问我在python应用程序的“main”部分中创建的Queue对象?

You can not modify the signature of the methods of the class that is inherited, so the solution in these cases is to pass the variable through an attribute of the class: 您无法修改继承的类的方法的签名,因此在这些情况下的解决方案是通过类的属性传递变量:

class FooWidget(QWidget):
    def __init__(self, q, parent=None):
        super(FooWidget, self).__init__(parent)
        self.m_q = q

    def paintEvent(self, event):
        painter = QPainter(self)
        self.drawMandelbrot(painter, self.m_q)

    def drawMandelbrot(sef, painter, q):
        # ... some code


if __name__ == '__main__':
    procQueue = Queue()
    app = QApplication([])
    w = FooWidget(procQueue)
    # ...

On the other hand, the paintEvent (and obviously drawMandelbrot) can only be executed in the main thread of the main process since Qt does not support multiprocessing, and the GUI must be executed in the GUI thread which is the main thread. 另一方面,paintEvent(显然是drawMandelbrot)只能在主进程的主线程中执行,因为Qt不支持多处理,并且GUI必须在作为主线程的GUI线程中执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM