我是Qt的新手,但需要解决一个棘手的问题.
我创建了一个非常简单的GUI,我需要将其添加到现有的C++应用程序中.问题是,我只写了一个插入更大架构的模块,这限制了我对主线程的访问.
我的代码必须驻留在以下四个函数中:一个Init()函数,它在主线程中运行.和在工作线程中运行的WorkerStart(),WorkerStep()和WorkerStop()函数.
我在Init()函数中编写了我的QApplication和GUI对象.但是,当然,在该函数末尾调用app.exec()会阻止整个代码.不可行.
我正在阅读的所有东西都说Qt gui对象只能在主线程中运行.
所以我的问题是,如何在init()函数(主线程)中设置我的gui并允许它从那时起仅使用工作线程运行?
我发现了这个:非主线程中的QApplication
那些解决方案给了我一些不同的行为.在正确的方向,但不稳定或完全功能.但我不明白为什么这些解决方案根本不存在qt gui只能在主线程中运行,而这些解决方案将它们放在其他线程中.因此,在其他线程中发送可以和不可以运行的内容的混合消息,这变得非常混乱.
似乎在现有的C++程序中添加gui而不将其锁定在exec()函数中应该是一个相当常见的情况,所以我觉得我错过了一些明显的东西.有人可以帮我解决这个问题吗?
非常感谢提前.菲尔
我有一个从两个QThreads主线程调用的方法.这个方法有时需要花费很长时间才能在循环中进行计算,所以我放了QCoreApplication::processEvents()这个就可以防止GUI冻结.在某些时候我已经改变QCoreApplication::processEvents()了QApplication::processEvents()但是这导致GUI冻结(我非常确定那是什么令人惊叹它因为我QCoreApplication::processEvents()放回它还没有再次冻结)我是正确的认为QApplication::processEvents()从主线程和QThreads调用可以冻结GUI?
我用PyQt制作端口扫描程序,但是当我激活循环时,Gui冻结.我怎么能解决这个问题?我添加了time.sleep()函数,但它仍然冻结.这是它冻结的功能.谢谢.
try:
time.sleep(1)
hostname=self.adres.text()
hostip=socket.gethostbyname(hostname)
uyari1="Scanning remote host, {}\n".format(hostip)
self.durum.append(uyari1)
print(uyari1)
for port in range(1,1025):
time.sleep(0.1)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((hostip, port))
if result == 0:
time.sleep(0.01)
print ("Port {}: \t Open".format(port))
self.durum.append("Port {}: \t Open\n".format(port))
sock.close()
Run Code Online (Sandbox Code Playgroud)
完整代码:
import socket,os,time
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig) …Run Code Online (Sandbox Code Playgroud) 创建一个 QMainWindow >> 按下开始按钮 >> 将长时间运行的函数与 QLabel 作为 arg >> 在运行长函数时更新标签。
我想更新 GUI 中长时间运行的函数的状态。但是一旦长时间运行的功能启动,整个窗口就会冻结
import sys
import time
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (
QApplication,
QLabel,
QMainWindow,
QPushButton,
QVBoxLayout,
QWidget,
)
def runLongTask(label):
label.setText('<1> sleeping for 10s ...')
time.sleep(10)
label.setText('<2> sleeping for 10s ...')
time.sleep(10)
label.setText('End')
class Window(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.setupUi()
def setupUi(self):
self.setWindowTitle("GUI freeze FIX")
self.resize(350, 250)
self.centralWidget = QWidget()
self.setCentralWidget(self.centralWidget)
self.label = QLabel()
self.label.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
self.label.setText('No Update')
countBtn = QPushButton("Start")
countBtn.clicked.connect(lambda: runLongTask(self.label))
layout …Run Code Online (Sandbox Code Playgroud)