如何从另一个线程向 gui 发送标签 - PyQt
How can I send a Label to gui from another thread - PyQt
这是一个简单的漫画 reader,我正在尝试在不冻结主体的情况下加载图像 window,我尝试使用线程来执行此操作但无法将图像发送到主体 window,我做错了什么?我也是python的新手,如果有其他方法我想知道谢谢。
from PyQt5 import QtCore, QtGui, QtWidgets
import os
class MainWin(QtWidgets.QMainWindow):
...
def add_widget(self, data):
self.verticalLayout.addWidget(data)
def file_open(self):
adres = QtWidgets.QFileDialog.getExistingDirectory()
self.loader = LoaderThread(adres)
self.loader.start()
self.loader.pics.connect(self.add_widget)
class LoaderThread(QtCore.QThread):
pics = QtCore.pyqtSignal(object)
def __init__(self, nAdres):
QtCore.QThread.__init__(self)
self.adres = nAdres
def run(self):
liste = os.listdir(self.adres)
order = 0
for i in liste:
label = QtWidgets.QLabel()
pixmap = QtGui.QPixmap(self.adres + '/' + liste[order])
label.setPixmap(pixmap)
self.pics.emit(label)
order += 1
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
win = MainWin()
win.show()
sys.exit(app.exec_())
您不能在 GUI 线程之外创建小部件或像素图。所以只要在worker线程中创建一个QImage
,然后在slot中创建label和pixmap即可:
class LoaderThread(QtCore.QThread):
...
def run(self):
liste = os.listdir(self.adres)
order = 0
for i in liste:
image = QtGui.QImage(self.adres + '/' + liste[order])
self.pics.emit(image)
order += 1
class MainWin(QtWidgets.QMainWindow):
...
def add_widget(self, image):
label = QtWidgets.QLabel()
label.setPixmap(QtGui.QPixmap.fromImage(image))
self.verticalLayout.addWidget(label)
这是一个简单的漫画 reader,我正在尝试在不冻结主体的情况下加载图像 window,我尝试使用线程来执行此操作但无法将图像发送到主体 window,我做错了什么?我也是python的新手,如果有其他方法我想知道谢谢。
from PyQt5 import QtCore, QtGui, QtWidgets
import os
class MainWin(QtWidgets.QMainWindow):
...
def add_widget(self, data):
self.verticalLayout.addWidget(data)
def file_open(self):
adres = QtWidgets.QFileDialog.getExistingDirectory()
self.loader = LoaderThread(adres)
self.loader.start()
self.loader.pics.connect(self.add_widget)
class LoaderThread(QtCore.QThread):
pics = QtCore.pyqtSignal(object)
def __init__(self, nAdres):
QtCore.QThread.__init__(self)
self.adres = nAdres
def run(self):
liste = os.listdir(self.adres)
order = 0
for i in liste:
label = QtWidgets.QLabel()
pixmap = QtGui.QPixmap(self.adres + '/' + liste[order])
label.setPixmap(pixmap)
self.pics.emit(label)
order += 1
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
win = MainWin()
win.show()
sys.exit(app.exec_())
您不能在 GUI 线程之外创建小部件或像素图。所以只要在worker线程中创建一个QImage
,然后在slot中创建label和pixmap即可:
class LoaderThread(QtCore.QThread):
...
def run(self):
liste = os.listdir(self.adres)
order = 0
for i in liste:
image = QtGui.QImage(self.adres + '/' + liste[order])
self.pics.emit(image)
order += 1
class MainWin(QtWidgets.QMainWindow):
...
def add_widget(self, image):
label = QtWidgets.QLabel()
label.setPixmap(QtGui.QPixmap.fromImage(image))
self.verticalLayout.addWidget(label)