在 QTreeView 中设置粗体行 [英] Set bold rows in a QTreeView
问题描述
我在 pyqt 应用程序中有一个 QTreeView 的自定义子类.我试图让用户能够突出显示和低亮"(因为缺乏更好的术语)行.突出显示的行应该有粗体文本和(可选)不同的背景颜色.有什么想法吗?
我正在考虑将样式表作为一种选择,但到目前为止还无法让它发挥作用.如果我设置 QTreeView 的样式表:
I have a custom subclass of a QTreeView in a pyqt application. I'm trying to give the user the ability to highlight and "lowlight" (for lack of a better term) rows. Highlighted rows should have bold text and (optionally) a different background color. Any ideas?
I'm considering StyleSheets as an option, but have so far been unable to get that to work. If I set the QTreeView's stylesheet:
self.setStyleSheet("QTreeView::item:selected {border: 1px solid #567dbc;}")
我不知道如何手动启用状态",以便仅将所需行保持在特定状态.如果我尝试设置单个项目的样式表:
I can't figure out how to manually enable 'states' that would keep only the desired rows at a particular state. If I try setting an individual item's stylesheet:
#modelIndex is a valid QModelIndex
modelIndex.internalPointer().setStyleSheet()
我遇到了段错误.
我不相信样式表是要走的路,我对所有想法持开放态度.谢谢!
I get a segfault.
I'm not convinced stylesheets are the way to go, I'm open to all ideas. Thanks!
推荐答案
从你所说的看来,最简单的解决方案是定义一个 自定义项目委托 用于您的树视图,并在需要时将项目字体粗细设置为粗体.请检查下面的示例是否适合您,它应该创建一个带有自定义项目委托的树视图,这将更改项目的字体样式.
From what you've said it looks like the easiest solution would be to define a custom item delegate for your treeview and set items font weight to bold whenever it's needed. Pls, check if an example below would work for you, it should create a treeview with custom item delegate which would change item's font style.
import sys
from PyQt4 import QtGui, QtCore
class BoldDelegate(QtGui.QStyledItemDelegate):
def paint(self, painter, option, index):
# decide here if item should be bold and set font weight to bold if needed
option.font.setWeight(QtGui.QFont.Bold)
QtGui.QStyledItemDelegate.paint(self, painter, option, index)
class MainForm(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainForm, self).__init__(parent)
model = QtGui.QStandardItemModel()
for k in range(0, 4):
parentItem = model.invisibleRootItem()
for i in range(0, 4):
item = QtGui.QStandardItem(QtCore.QString("item %0 %1").arg(k).arg(i))
parentItem.appendRow(item)
parentItem = item
self.view = QtGui.QTreeView()
self.view.setModel(model)
self.view.setItemDelegate(BoldDelegate(self))
self.setCentralWidget(self.view)
def main():
app = QtGui.QApplication(sys.argv)
form = MainForm()
form.show()
app.exec_()
if __name__ == '__main__':
main()
希望对您有所帮助,问候
hope this helps, regards
这篇关于在 QTreeView 中设置粗体行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!