Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python PyQt5-如何更改列表小部件中的特定项目背景颜色_Python_Pyqt5 - Fatal编程技术网

Python PyQt5-如何更改列表小部件中的特定项目背景颜色

Python PyQt5-如何更改列表小部件中的特定项目背景颜色,python,pyqt5,Python,Pyqt5,这个程序有一个简单的列表小部件。如何在不单击列表中任何特定项的情况下更改其背景色 from PyQt5 import QtWidgets, uic, QtGui import threading app = QtWidgets.QApplication([]) ui = uic.loadUi("app.ui") update_ui = True ui.lst_positions.addItem("Item 1") ui.lst_positions.a

这个程序有一个简单的列表小部件。如何在不单击列表中任何特定项的情况下更改其背景色

from PyQt5 import QtWidgets, uic, QtGui
import threading

app = QtWidgets.QApplication([])
ui = uic.loadUi("app.ui")

update_ui = True

ui.lst_positions.addItem("Item 1")
ui.lst_positions.addItem("Item 2")
ui.lst_positions.addItem("Item 3")


def ui_update():
    while update_ui == True:
        # Updating labels works fine with threading
        ui.lbl_in_position.setText("Random text")
        # This does not work with threading
        item = ui.lst_positions.item(1)
        item.setBackground(QtGui.QColor("red"))


ui_thread = threading.Thread(target=ui_update)
ui_thread.daemon = True

ui_thread.start()

ui.show()
app.exec()

任务很简单:

  • 获取与索引关联的QListWidgetItem
  • 使用QListWidgetItem的setBackground方法
item=ui.lst\u positions.item(项目编号变更)
项目背景(QtGui.QColor(“红色”))
更新:

问题是,您不应该从另一个线程更新GUI,因为GUI的元素不是线程安全的,所以您会收到您在注释中指出的警告。一种解决方案是创建一个QObject,它有信号(线程安全)在线程之间交换信息

#。。。
等级信号员(QtCore.QObject):
textChanged=QtCore.pyqtSignal(str)
itemChanged=QtCore.pyqtSignal(int,QtGui.QColor)
定义ui_更新(qobject):
当update_ui==True时:
qobject.textChanged.emit(“随机文本”)
qobject.itemChanged.emit(i,QtGui.QColor(“红色”))
def foo(i,颜色):
项目=ui.lst\U位置。项目(i)
如果项目:
项目.背景(颜色)
信号员
signaller.textChanged.connect(ui.lbl\u处于位置。setText)
信号器.itemChanged.connect(foo)
ui\u thread=threading.thread(target=ui\u update,args=(signaller,))
ui_thread.daemon=True
ui_thread.start()
# ...
注意:仅仅因为文本显示正确并不意味着它是正确的。如果GUI是从另一个线程直接更新的,Qt不能保证(这意味着它可能会失败)正确的操作