<p>Qt的模型视图架构允许数据描述正在执行的<a href="http://doc.trolltech.com/4.7/qt.html#ItemDataRole-enum" rel="nofollow noreferrer">different roles</a>。例如,有一个角色用于编辑数据、显示数据等。您对字体角色(即<code>Qt::FontRole</code>)感兴趣,因为<a href="http://doc.trolltech.com/4.7/qfont.html" rel="nofollow noreferrer">font</a>有一个<a href="http://doc.trolltech.com/4.7/qfont.html#Weight-enum" rel="nofollow noreferrer">weight</a>枚举,粗体是一个值。在</p>
<p>在构建分支时,首先需要确定哪些项应该加粗。我假设你有这样一种方法,可以确定他们是否应该加粗:</p>
<pre><code>def should_be_bolded(self, item):
return 1 # your condition checks
</code></pre>
<p>现在只需设置字体的权重并使用其<a href="http://doc.trolltech.com/4.7/qstandarditem.html#setData" rel="nofollow noreferrer">setData</a>方法设置项的字体角色:</p>
^{pr2}$
<p>但是等等。。。您已经有了qStandardItem的子类,因此可以使用它:</p>
<pre><code>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()
</code></pre>
<p>您将不得不修复<code>should_be_bolded</code>和<code>bold_myself</code>方法,并相应地进行清理,但希望您能理解要点。在</p>
<p>Stephen <a href="https://stackoverflow.com/questions/7097881/how-do-i-change-the-colour-of-a-specific-branch-within-qtreeview/7098762#7098762">pointed out</a>,您也可以将其中一个<code>QAbstractItemModel</code>子类化,就像您使用的<code>QStandardItemModel</code>,并返回一个特定的<code>Qt.FontRole</code>。他的方法使这种知识隐含在模型中。决定知识最应该属于哪里,并把它放在最合适的地方,不管是在项目、树创建算法、模型,甚至是视图模型中。在</p>