ZBLOG

使用代码控制父子节点的偏移值

在QTreeView中,可以通过自定义代理类来实现控制父子节点的偏移值。以下是一个示例:

from PyQt5.QtWidgets import QApplication, QTreeView, QStyledItemDelegate
from PyQt5.QtCore import QModelIndex


class IndentDelegate(QStyledItemDelegate):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.indentation = 20

    def paint(self, painter, option, index):
        if index.parent().isValid():
            option.rect.adjust(self.indentation, 0, 0, 0)
        super().paint(painter, option, index)

    def sizeHint(self, option, index):
        size = super().sizeHint(option, index)
        if index.parent().isValid():
            size.setWidth(size.width() + self.indentation)
        return size


app = QApplication([])
treeview = QTreeView()
model = treeview.model()

delegate = IndentDelegate()
treeview.setItemDelegate(delegate)

# 设置根节点数据
model.setHorizontalHeaderLabels(["Name", "Description"])
root_node = model.invisibleRootItem()
root_node.appendRow([QStandardItem("Parent Node"), QStandardItem("Description of Parent Node")])

# 添加子节点数据
child_node1 = QStandardItem("Child Node 1")
child_node2 = QStandardItem("Child Node 2")
root_node.setChild(0, child_node1)
root_node.setChild(1, child_node2)

treeview.expandAll()
treeview.show()
app.exec_()

上述代码中,我们创建了一个自定义的代理类IndentDelegate,通过重写paintsizeHint方法来控制父子节点的偏移值。你可以调整indentation变量的值来改变偏移量。

希望对你有所帮助!


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=15644

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?