使用 pyqt 进行多线程处理 - 无法同时运行单独的线程?
我正在尝试让 PyQT GUI 在我的 python 应用程序之上运行,并且尝试将其分成 2 个线程,以便 GUI 在我的主运行循环运行时能够做出响应,但我无法让它运行。也许我误解了它。这是我尝试过的:
我的 Window
和 Worker
线程定义如下:
class Window(QWidget):
def __init__(self, parent = None):
QWidget.__init__(self, parent)
self.thread = Worker()
start = QPushButton("Start", self)
QObject.connect(start, SIGNAL("clicked()"), MAIN_WORLD.begin)
hbox = QVBoxLayout(self)
hbox.addStretch(4)
class Worker(QThread):
def __init__(self, parent = None):
QThread.__init__(self, parent)
if __name__ == '__main__':
MAIN_WORLD = World()
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
这似乎与在线示例非常接近。我的 World 类正在运行一个无限循环,一旦用户单击“开始”,直到再次单击。这是它的定义的一部分。
class World(QThread):
def __init__(self, parent = None):
QThread.__init__(self, parent)
self.currentlyRunning = False
//snip
def begin(self):
if self.currentlyRunning:
self.currentlyRunning = False
else:
self.currentlyRunning = True
self.MethodThatDoesUsefulStuff()
编辑:我注意到我并没有真正“使用”我的工作线程。如何创建我的世界线程作为工作线程?
I am trying to get a PyQT GUI running ontop of my python application and I have tried to get it separated into 2 threads so the GUI would be responsive while my main running loop goes, but I have not been able to get it going. Maybe I am misunderstanding it. Here is what I've tried:
My Window
and Worker
thread are defined as follows:
class Window(QWidget):
def __init__(self, parent = None):
QWidget.__init__(self, parent)
self.thread = Worker()
start = QPushButton("Start", self)
QObject.connect(start, SIGNAL("clicked()"), MAIN_WORLD.begin)
hbox = QVBoxLayout(self)
hbox.addStretch(4)
class Worker(QThread):
def __init__(self, parent = None):
QThread.__init__(self, parent)
if __name__ == '__main__':
MAIN_WORLD = World()
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
which seems to follow very closely to online examples. My World
class is running a loop that is infinite once the user clicks "Start" until it's clicked again. Here is part of the definition of it.
class World(QThread):
def __init__(self, parent = None):
QThread.__init__(self, parent)
self.currentlyRunning = False
//snip
def begin(self):
if self.currentlyRunning:
self.currentlyRunning = False
else:
self.currentlyRunning = True
self.MethodThatDoesUsefulStuff()
edit: I have noticed that I'm not really "using" my worker thread. How do I create my world thread as a worker thread?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
更仔细地查看代码后,您发现 MAIN_WORLD 在 QApplication 之前启动,这不是您想要的。
您想要做这样的事情:
并且,在您的 Window 类中:
上面的内容将允许主线程控制 gui 并允许工作线程在后台工作。
After looking more closely at your code, you have MAIN_WORLD started before QApplication, which isn't what you want.
You want to do something like this:
And, in your Window class:
The above will allow the main thread to control the gui and allow the worker threads to work in the background.
当然,这是 PyQt 而不是 PySide,但是:
Granted that is PyQt and not PySide, but: