我对QTreeWidget有点迷茫,无法从找到的主题中吸收相关信息(例如:how to set QTreeView background image with QStyle::StandardPixmap in stylesheet method?或Python: PyQt QTreeview example - selection或Styling Qt QTreeView with CSS或Displaying tabular data in Qt5 ModelViews。
我有两个文件,一个是gui,一个是工人阶级:
gui:
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
self.tree = QtWidgets.QTreeWidget(Dialog)
self.tree.setGeometry(QtCore.QRect(10, 60, 760, 480))
self.tree.setHeaderLabels(['circ', 'state', 'test'])
self.tree.setSortingEnabled(True)
worker:
class AppWindow(QDialog):
def __init__(self, fullscreen=False):
super().__init__()
self.ui = Ui_Dialog()
self.ui.setupUi(self)
self.show()
self.timer = QTimer()
self.timer.setInterval(500)
self.timer.timeout.connect(self.refresh_gui)
self.timer.start()
def refresh_tree(self):
self.painter = QPainter(self)
tmp = {0: {"state": 1, "info": "hello"}, 1: {"state": 0, "info": "world"}}
for i in tmp:
if tmp[i]["state"] == 0:
painter.setPen(QPen(Qt.red, 8, Qt.SolidLine))
else:
painter.setPen(QPen(Qt.green, 8, Qt.SolidLine))
circ = painter.drawEllipse(2,2,20,20)
item = QtWidgets.QTreeWidgetItem(self.ui.tree, [circ, tmp[i]["state"], "empty"])
item.setText(2, "circ painted")
[我想实现,如果state == 0
第一栏中显示一个红色圆圈,如果state == 1
为绿色一个圆圈。我不知道如何将QTreeWidgetItem传递给PyQt5.QtGui.QPainter对象而不是字符串。
另外,我确实收到错误:
QStandardPaths: XDG_RUNTIME_DIR not set, defaulting to '/tmp/runtime-root'
QWidget::paintEngine: Should no longer be called
QPainter::begin: Paint device returned engine == 0, type: 1
QPainter::setPen: Painter not active
QPainter::end: Painter not active, aborted
和一些行降低(由于它):QPainter::setPen: Painter not active
因为我调用了self.painter = QPainter(self)
,而该文档已在in this git issue from matplotlib中讨论,但我无法在代码中对其进行修复。我发现此QPainter tutorial可以画在QPixmpa上,它也对我有用,但不是我在这里寻找的东西。
class Delegate(QtWidgets.QStyledItemDelegate):
def paint(self, painter, option, index):
state = index.data(QtCore.Qt.UserRole)
color = (
QtGui.QColor(QtCore.Qt.red) if state == 0 else QtGui.QColor(QtCore.Qt.green)
)
painter.setPen(QtGui.QPen(color, 4, QtCore.Qt.SolidLine))
diameter = min(option.rect.width(), option.rect.height())
rect = QtCore.QRect(0, 0, diameter // 2, diameter // 2)
rect.moveCenter(option.rect.center())
painter.drawEllipse(rect)
class AppWindow(QtWidgets.QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.ui = Ui_Dialog()
self.ui.setupUi(self)
self.show()
delegate = Delegate(self.ui.tree)
self.ui.tree.setItemDelegateForColumn(0, delegate)
self.timer = QtCore.QTimer(interval=500, timeout=self.refresh_gui)
self.timer.start()
@QtCore.pyqtSlot()
def refresh_gui(self):
tmp = [{"state": 1, "info": "hello"}, {"state": 0, "info": "world"}]
for d in tmp:
item = QtWidgets.QTreeWidgetItem(self.ui.tree, ["", str(d["state"]), "empty"])
item.setData(0, QtCore.Qt.UserRole, d["state"])
item.setText(2, "circ painted")