我想让这一行没有展开的胡萝卜,但仍然可以被选择。
我试过这个:
import sys
from PySide2.QtWidgets import QApplication, QMainWindow, QTreeView, QVBoxLayout, QWidget, QAbstractItemView, QSizePolicy, QStyledItemDelegate
from PySide2.QtCore import Qt, QModelIndex
class CustomItemDelegate(QStyledItemDelegate):
def sizeHint(self, option, index):
size = super().sizeHint(option, index)
if index.row() == self.model.max_display_rows:
size.setWidth(0) # Hide the expanding icon
return size
class CustomItemModel(QAbstractItemModel):
def __init__(self, data, parent=None):
super().__init__(parent)
self.data = data
self.max_display_rows = 5
# ... (rest of the model methods)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Custom Item Model Example")
self.setGeometry(100, 100, 400, 300)
data = ["Item {}".format(i) for i in range(1, 11)]
self.model = CustomItemModel(data)
self.treeView = QTreeView()
self.treeView.setModel(self.model)
self.treeView.setSelectionBehavior(QAbstractItemView.SelectRows)
self.treeView.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
delegate = CustomItemDelegate(self.treeView)
self.treeView.setItemDelegate(delegate)
layout = QVBoxLayout()
layout.addWidget(self.treeView)
central_widget = QWidget()
central_widget.setLayout(layout)
self.setCentralWidget(central_widget)
def main():
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
不起作用。
您可以执行类似的操作来不绘制箭头并且不展开项目。
class TreeView(QTreeView):
def drawBranches(self, painter, rect, index):
if index.row() == self.model().max_display_rows:
return # do not draw branch
super().drawBranches(painter, rect, index)
class MainWindow(QMainWindow):
def __init__(self):
...
self.treeView = TreeView()
self.treeView.expanded[QModelIndex].connect(
lambda index: index.row() == self.treeView.model().max_display_rows and self.treeView.collapse(index)
) # immediately collapse index
...