[英]how to update pyqt5 GUI label led icons(pixmap)
我有包含所有线程和字典的 main.py 文件,一个是我在 main.py 文件中定义的 GUI 线程。
现在在我的 gui 线程中,我定义了一个 function 到
gui.py
class Ui_MainWindow(object):
def setupUi(self, MainWindow, object_dictionary):
self.closed_led = QtWidgets.QLabel(self.central_widget)
self.closed_led.setGeometry(QtCore.QRect(910, 70, 61, 61))
self.closed_led.setText("")
self.closed_led.setPixmap(QtGui.QPixmap("black.jpg"))
self.closed_led.setScaledContents(True)
self.closed_led.setObjectName("closed_led")
self.update_label(object_dictionary)
self.timer = QTimer()
self.timer.timeout.connect(lambda: self.update_label(object_dictionary))
self.timer.start(1000) # repeat self.update_label every 1 sec
def update_label(self, object_dictionary):
if object_dictionary['fridge_closed'] != 0:
self.closed_led.setPixmap(QtGui.QPixmap("green.jpg"))
print("green")
else:
self.closed_led.setPixmap(QtGui.QPixmap("black.jpg"))
print("black")
但我希望此更新标签继续检查字典中是否有任何输入,如果冰箱关闭 = 1,则 LED 应变为绿色,如果冰箱关闭 = 0,则 LED 应自动变为黑色。 我是否需要为此使用工作线程,如果是,那么如何分配信号槽。
您可以使object_dictionary
成为 Gui class 的成员,并将所有编辑内容包装到一个发出信号的方法中。 当您需要在 class 之外编辑字典时,只需使用 class 实例中的editDictionary()
即可。
class MainWindow(QtWidgets.QWidget):
# Signal for when dictionary is changed
objectDictionaryChanged = QtCore.Signal()
def __init__(self):
super(MainWindow, self).__init__()
self.mainLayout = QtWidgets.QVBoxLayout()
self.setLayout(self.mainLayout)
# Object dictionary becomes part of the class
self.object_dictionary = {}
self.closed_led = QtWidgets.QLabel()
# A spinbox that edits the value of 'fridge_closed' in the dictionary
self.dictionarySpinBox = QtWidgets.QSpinBox()
self.dictionarySpinBox.setMinimum(0)
self.dictionarySpinBox.setMaximum(1)
# The connections that handle the changes
self.objectDictionaryChanged.connect(self.update_label)
self.dictionarySpinBox.valueChanged.connect(
lambda: self.editDictionary('fridge_closed', self.dictionarySpinBox.value())
)
self.mainLayout.addWidget(self.closed_led)
self.mainLayout.addWidget(self.dictionarySpinBox)
self.dictionarySpinBox.setValue(1)
def editDictionary(self, key, value):
# All edits to object dictionary should pass through here
self.object_dictionary[key] = value
self.objectDictionaryChanged.emit()
def update_label(self):
state = self.object_dictionary['fridge_closed']
if state is 0:
self.closed_led.setPixmap(QtGui.QPixmap("black.jpg"))
elif state is 1:
self.closed_led.setPixmap(QtGui.QPixmap("green.jpg"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.