简体   繁体   中英

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.

I have tried to use global python lists but lists don't work with the multiprocessing library. In the "main" section of my code I create a multiprocess.Queue object. The function drawMandelbrot is part of my QWidget class and is executed by the paintEvent. The paint event runs whenever the gui window needs to be drawn on the screen. But the function drawMandelbrot needs to access the Queue object to get data that needs to be drawn.

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. When the program is run it gives the error "TypeError: paintEvent() missing 1 required positional argument: '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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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