PyQt5 QtreeView
时间: 2023-09-12 07:03:42 浏览: 110
QTreeView应用
PyQt5 QTreeView is a flexible and powerful widget for displaying hierarchical data. It is used to display data in a tree-like structure with parent-child relationships.
QTreeView class inherits from QAbstractItemView class, which provides the basic functionality for displaying data from models created by QAbstractItemModel.
To use QTreeView in PyQt5, you first need to create a model that inherits from QAbstractItemModel, which is responsible for managing the data to be displayed in the tree view.
Here is an example of creating a simple QTreeView:
```python
from PyQt5.QtWidgets import QApplication, QTreeView
from PyQt5.QtCore import QAbstractItemModel, QModelIndex, Qt
class TreeModel(QAbstractItemModel):
def __init__(self, data, parent=None):
super().__init__(parent)
self._data = data
def columnCount(self, parent):
return 1
def rowCount(self, parent):
if not parent.isValid():
return len(self._data)
return 0
def data(self, index, role):
if not index.isValid():
return None
if role == Qt.DisplayRole:
return self._data[index.row()]
return None
def index(self, row, column, parent):
if not parent.isValid():
return self.createIndex(row, column)
return QModelIndex()
def parent(self, index):
return QModelIndex()
if __name__ == '__main__':
app = QApplication([])
data = ['Item 1', 'Item 2', 'Item 3', 'Item 4']
model = TreeModel(data)
tree_view = QTreeView()
tree_view.setModel(model)
tree_view.show()
app.exec_()
```
In this example, we have created a TreeModel class that inherits from QAbstractItemModel. The model takes a list of data as an argument and implements the required methods for managing the data, such as rowCount(), columnCount(), data(), index(), and parent().
We then create an instance of the TreeModel class with the data list and set it as the model for the QTreeView widget. Finally, we show the QTreeView widget and start the application event loop.
This example creates a very basic tree view with only one column and no parent-child relationships. In practice, you would typically create a more complex model that represents hierarchical data with multiple columns and parent-child relationships.
QTreeView provides a lot of customization options, such as customizing the appearance of the tree view, drag and drop support, and editing items in the tree view. You can find more information about these features in the PyQt5 documentation.
阅读全文