简体   繁体   English

pyqt4中的线程错误

[英]Error with thread in pyqt4

I have the problem. 我有问题。 I made the thread and from there I want to open the new window. 我创建了线程,然后从那里打开新窗口。 But it does not work. 但这行不通。

import sys
from grab import Grab
from PyQt4 import QtGui, QtCore
class Requests(QtCore.QThread):
    def __init__(self, parent=None):
        QtCore.QThread.__init__(self, parent)

    def run(self):
        # here some comands
        self.emit(QtCore.SIGNAL("mysignal(QString)"), 'open')

class window(QtGui.QWidget):
    def __init__(self, parent = None):
        QtGui.QWidget.__init__(self, parent)

        self.setGeometry(100, 100, 500, 200)
        self.setWindowTitle('Window')
        self.label = QtGui.QLabel(u'Hello')
        self.Layout = QtGui.QVBoxLayout()
        self.Layout.addWidget(self.label)
        self.setLayout(self.Layout)

        self.c = Requests()
        self.c.start()
        self.connect(self.c, QtCore.SIGNAL("mysignal(QString)"), self.open_window, QtCore.Qt.QueuedConnection)

    def open_window(self):
        print 'open modal window'
        modal_w = popup_window()
        modal_w.show()

app = QtGui.QApplication(sys.argv)
main = window()
main.show()
sys.exit(app.exec_())

It is not show new window. 它不显示新窗口。 Where is the error? 错误在哪里?

You need to connect the signal before the thread starts, and hence before the signal is emitted. 您需要在线程启动之前(因此在发出信号之前)连接信号。 If you want to show a dialog when the worker thread completes, just use the finished signal: 如果要在工作线程完成时显示对话框,请使用finished信号:

class Requests(QtCore.QThread):    
    def run(self):
        # do some work...
        print 'work finished'

    ...
    self.c = Requests()
    self.c.finished.connect(self.open_window)
    self.c.start()

You also need to keep a reference to the dialog when opening it in the slot: 在插槽中打开对话框时,还需要保留对对话框的引用:

    def open_window(self):
        print 'open modal window'
        self.modal_w = popup_window()
        self.modal_w.show()

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

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