gpt4 book ai didi

python - 如何更改 QTreeView 中特定分支的颜色?

转载 作者:太空宇宙 更新时间:2023-11-03 19:28:45 28 4
gpt4 key购买 nike

我有一个 QTreeView,并且我已经弄清楚如何通过在我的主类中使用 setStyleSheet 设置其样式:

self.view.setStyleSheet("""
QTreeView::item {
margin: 2px;
}
""")

这将为整个 QTreeView 设置样式。但我希望树中的某些项目加粗。当我创建分支时(使用[父小部件].appendRow("项目的名称")),有没有办法“标记”或隔离特定项目,以便可以将其样式设置为同样的方式?我认为答案与“AccessibleName”或“ObjectName”属性有关,但我找不到相关文档。

更新:这是我到目前为止所拥有的:

#!/usr/bin/python
# -*- coding: utf-8 -*-

from __future__ import division
from __future__ import print_function
from future_builtins import *

import os, sys
from PySide.QtCore import *
from PySide.QtGui import *

path_to_media = '/Volumes/show/vfx/webisodes/%d1%/seq/%d2%/%d3%/renders/2d/comp/'

class FileTree(QTreeView):
"""Main file tree element"""
def __init__(self):
QTreeView.__init__(self)
def keyPressEvent(self, event):
if event.key() == Qt.Key_Space or event.key() == Qt.Key_Return:
index = self.selectedIndexes()[0]
crawler = index.model().itemFromIndex(index)
if crawler.uri:
print("launching", crawler.uri)
p = os.popen(('open -a "RV.app" "'+ crawler.uri) +'"', "r")
QTreeView.keyPressEvent(self, event)

class Branch(QStandardItem):
"""Branch element"""
def __init__(self, label, uri = None, tag = None):
QStandardItem.__init__(self, label)
self.uri = uri

class AppForm(QMainWindow):
def __init__(self, parent = None):
super(AppForm, self).__init__(parent)
self.model = QStandardItemModel()
self.view = FileTree()
self.view.setStyleSheet("""
QTreeView::item {
margin: 2px;
}
""")
self.view.setEditTriggers(QAbstractItemView.NoEditTriggers)
self.view.setModel(self.model)
self.setCentralWidget(self.view)
self.Grow()
# self.view.setSortingEnabled(True)

def Grow(self):
"""Populates FileTree (using BuildBranch())"""
global path_to_media
self.path = {}
self.path['source'] = path_to_media
self.path['parts'] = []
self.path['depth'] = 0
self.path['crawl'] = {}
for i in self.path['source'].split('%'):
if i[0] == "d" and i[1].isdigit():
self.path['depth'] += 1
else:
self.path['parts'].append(i)
self.BuildBranch(self.path['parts'], self.path['depth'], parentWidget = self.model.invisibleRootItem())

def BuildBranch(self, parts, depth, uri = '', count = 0, parent = '', parentWidget = ''):
"""Recursively crawls folder structure and adds appropriate branches"""
if not uri: uri = parts[0]
else: uri += parent + parts[count]
try:
if os.listdir(uri):
for i in os.listdir(uri):
if i[0] != '.':
if count != depth:
if os.path.isdir(uri):
thisWidget = Branch(i)
parentWidget.appendRow(thisWidget)
self.BuildBranch(parts, depth, uri, count + 1, i, parentWidget = thisWidget)
else:
thisWidget = Branch(i)
parentWidget.appendRow(thisWidget)
elif count == depth:
thisWidget = Branch(i, uri + i, 'media')
parentWidget.appendRow(thisWidget)
else:
print("nothing here; nuking " + parent)
# Need to add code to nuke unused branch
except OSError:
print("Folder structure error... nuking the branch")
# Need to add code to nuke unused branch

def main():
app = QApplication(sys.argv)
form = AppForm()
form.resize(800, 600)
form.setWindowTitle('Qt Dailies')
form.show()
app.exec_()

if __name__ == "__main__":
main()

更新 2: 好的,我修改了我的 Branch 类,以便如果将“bold”传递给它,它会使分支变为粗体(理论上)...

class Branch(QStandardItem):
def __init__(self, label, uri = None, tag = None):
QStandardItem.__init__(self, label)
self.uri = uri
if tag == 'bold':
self.setData(self.createBoldFont(), Qt.FontRole)
def createBoldFont(self):
if self.font: return self.font
self.font = QFont()
self.font.setWeight(QFont.Bold)
return self.font

...但是当代码运行时,似乎什么也没有发生。我还没有得到什么?

最佳答案

Qt 的模型 View 架构允许描述different roles 的数据。正在执行。例如,有一个用于编辑数据、显示数据等的角色。您对字体角色(即 Qt::FontRole)感兴趣,如 font有一个weight枚举,其中粗体是一个值。

当您构建分支时,您首先需要确定哪些项目应加粗。我假设您有一个类似的方法可以识别它们是否应该为粗体:

def should_be_bolded(self, item):
return 1 # your condition checks

现在只需设置字体的粗细并使用其setData设置项目的字体角色。方法:

def BuildBranch(...):
thisWidget = Branch(i)
if self.should_be_bolded(thisWidget):
thisWidget.setData(self.createBoldFont(), Qt.FontRole)

def createFont(self):
if self.font: return self.font
self.font = QFont()
self.font.setWeight(QFont.Bold)
return self.font

但是等等...您已经有了 QtandardItem 的子类,因此您可以使用它:

class Branch(QStandardItem):
"""Branch element"""
def __init__(self, label, uri = None, tag = None):
QStandardItem.__init__(self, label)
self.uri = uri
if self.should_be_bolded():
self.bold_myself()

您必须修复 should_be_boldedbold_myself 方法,进行相应的清理,但希望您能明白这一点。

斯蒂芬pointed out您还可以对 QAbstractItemModel 之一进行子类化,例如您正在使用的 QStandardItemModel,并返回特定的 Qt.FontRole。他的方法使这些知识隐含在模型中。确定知识最适合的位置并将其放置在最合适的位置,无论是在项目中、树创建算法中、模型中,甚至是 View 模型中。

关于python - 如何更改 QTreeView 中特定分支的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7097881/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com