我如何扩展 QTreeView 项目,知道它是 modelIndex。我正在尝试调用以下代码,它不会引发任何错误,但不会扩展树视图项...
parentIndex = self.categoryModel.indexFromItem(parent)
if parentIndex.isValid():
self.uiTreeView.setExpanded(parentIndex, True)
要进行测试,请选择列表中的第一项并单击“添加”按钮。当用户添加一个新类别时,我希望它扩展它被添加到的项目。
import os, sys
from Qt import QtWidgets, QtGui, QtCore
################################################################################
# Widgets
################################################################################
class CategoryView(QtWidgets.QWidget):
def __init__(self):
QtWidgets.QWidget.__init__(self)
self.resize(250,400)
self.uiAdd = QtWidgets.QPushButton('Add')
self.categoryModel = QtGui.QStandardItemModel()
self.categoryModel.setHorizontalHeaderLabels(['Items'])
self.categoryProxyModel = QtCore.QSortFilterProxyModel()
self.categoryProxyModel.setSourceModel(self.categoryModel)
self.categoryProxyModel.setFilterCaseSensitivity(QtCore.Qt.CaseInsensitive)
self.categoryProxyModel.setSortCaseSensitivity(QtCore.Qt.CaseInsensitive)
self.categoryProxyModel.setDynamicSortFilter(True)
self.uiTreeView = QtWidgets.QTreeView()
self.uiTreeView.setModel(self.categoryProxyModel)
self.uiTreeView.sortByColumn(0, QtCore.Qt.AscendingOrder)
self.uiTreeView.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
self.layout = QtWidgets.QVBoxLayout()
self.layout.setContentsMargins(0,0,0,0)
self.layout.setSpacing(0)
self.layout.addWidget(self.uiAdd)
self.layout.addWidget(self.uiTreeView)
self.setLayout(self.layout)
# Selections
self.categorySelection = self.uiTreeView.selectionModel()
# Signals
self.uiAdd.clicked.connect(self.slotAddNewCategory)
parent = self.categoryModel.invisibleRootItem()
parent.appendRow(QtGui.QStandardItem('Fruit'))
# Methods
def getSelectedItems(self):
items = []
for proxyIndex in self.categorySelection.selectedIndexes():
sourceIndex = self.categoryProxyModel.mapToSource(proxyIndex)
item = self.categoryModel.itemFromIndex(sourceIndex)
items.append(item)
return items
def slotAddNewCategory(self):
text, ok = QtWidgets.QInputDialog.getText(self, 'Input Dialog', 'Enter your name:')
if ok:
item = QtGui.QStandardItem(text)
parent = self.categoryModel.invisibleRootItem()
items = self.getSelectedItems()
if len(items) == 1:
parent = items[0]
parent.appendRow(item)
parentIndex = self.categoryModel.indexFromItem(parent)
print parentIndex.data()
if parentIndex.isValid():
self.uiTreeView.setExpanded(parentIndex, True)
################################################################################
# Unit Testing
################################################################################
def test_CategoryView():
app = QtWidgets.QApplication(sys.argv)
ex = CategoryView()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
pass
test_CategoryView()
# test_PainterSettingsDialog()