Question

I tried to receive a string from a thread to my main GUI using SIGNALs. Everything works fine until I want to use the string in a QMessageBox. Printing out is no problem but starting a QMessageBox gives me several errors (some are about QPixmap which I even do not use in the GUI.

Here is a short working example of my code:

import sys
import urllib2
import time
from PyQt4 import QtCore, QtGui


class DownloadThread(QtCore.QThread):
    def __init__(self):
        QtCore.QThread.__init__(self)


    def run(self):
        time.sleep(3)
        self.emit(QtCore.SIGNAL("threadDone(QString)"), 'test')


class MainWindow(QtGui.QWidget):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.list_widget = QtGui.QListWidget()
        self.button = QtGui.QPushButton("Start")
        self.button.clicked.connect(self.start_download)
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.button)
        layout.addWidget(self.list_widget)
        self.setLayout(layout)

        self.downloader = DownloadThread()
        self.connect(self.downloader, QtCore.SIGNAL("threadDone(QString)"), self.threadDone, QtCore.Qt.DirectConnection)

    def start_download(self):
        self.downloader.start()

    def threadDone(self, info_message):
        print info_message
        QtGui.QMessageBox.information(self,
                    u"Information",
                    info_message
                    )
        #self.show_info_message(info_message)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    window = MainWindow()
    window.resize(640, 480)
    window.show()
    sys.exit(app.exec_())

I'm getting this erros:

QObject::setParent: Cannot set parent, new parent is in a different thread

QPixmap: It is not safe to use pixmaps outside the GUI thread

This error only while moving the mouse and QMessageBox is still open:

QObject::startTimer: timers cannot be started from another thread

QApplication: Object event filter cannot be in a different thread.

Can anyone tell me what I'm doing wrong?

This is the first time I'm using threads.

Thank you! Stefanie

Was it helpful?

Solution

QtCore.Qt.DirectConnection -- this option means that the slot will be called from the signal's thread. Your code has (at least) two threads running: the main GUI thread and the DownloadThread. So, with this option, the program tries to invoke threadDone from DownloadThread, and tries to create a GUI object outside the GUI thread.

This leads to: QPixmap: It is not safe to use pixmaps outside the GUI thread

Remove this option and the default behavior (wait to return to main thread before invoking the slot) should clear up the error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top