Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. Qt for Python
  4. Custom model development for QTreeView

Custom model development for QTreeView

Scheduled Pinned Locked Moved Solved Qt for Python
3 Posts 2 Posters 1.9k Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • T Offline
    T Offline
    tilz0R
    wrote on 23 Feb 2023, 17:04 last edited by
    #1

    I have a QTreeView and would like to develop custom model. In the final usage, I'm using SQLite to get table, and then with one-to-many relationship, to display its parameters at second level.

    For first tests, I have 2 classes: MyItem and MyItemParam, that both provide data to display. First one also holds array of second one (one MyItem has many MyItemParam classes).

    This is the direct example I made. I'm obviously struggling to get the correct data. I think main failure I have is around parent and index methods.

    Is there a good example to build custom model? I simply do not like to use QStandardItemModel for each of the line. I'd rather provide data as one big source, and then use model, to construct necessary tree.

    You can run the script directly. PySide 6.4.2 was used for the tests.

    What I want:
    247d9010-c90a-4316-8b1d-4fd8f7437b09-image.png

    import sys
    from PySide6.QtWidgets import *
    from PySide6.QtCore import *
    from PySide6.QtUiTools import *
    
    # Item object with name, title and parameters
    class MyItem():
        def __init__(self, name, title):
            self.name = name
            self.title = title
            self.params = []
    
        def add_param(self, param):
            self.params.append(param)
    
    # MyItemParam with key and value
    class MyItemParam():
        def __init__(self, key, value):
            self.key = key
            self.value = value
    
    # Treeview model
    class TreeModel(QAbstractItemModel):
        def __init__(self):
            super().__init__()
            self._data = []
    
        # Columns and rows
        def columnCount(self, parent):  return 2
        def rowCount(self, parent):     
            if parent.isValid():
                item = parent.internalPointer()
                if isinstance(item, MyItem):
                    return len(item.params)
                else:
                    return 0
            return len(self._data)
    
        # Index creation
        def index(self, row, column, parent = QModelIndex()):
            if parent.isValid():
                item = parent.internalPointer()
                if isinstance(item, MyItem):
                    item = item.params[row]
            else:
                item = self._data[row]
            return self.createIndex(row, column, item)
    
        # Parent object
        def parent(self, index):
            if not index.isValid():
                return QModelIndex()
            item = index.internalPointer()
            return self.createIndex(index.row(), index.column(), item)
            
        # Get data
        def data(self, index, role):
            item = index.internalPointer()
            if role == Qt.ItemDataRole.DisplayRole:
                column = index.column()
                # Print Item data
                if isinstance(item, MyItem):
                    if column == 0:
                        return item.name
                    elif column == 1:
                        return item.title
                # Print param data
                elif isinstance(item, MyItemParam):
                    if column == 0:
                        return item.key
                    elif column == 1:
                        return item.value
            return None
    
        # Add data to the model
        def load_custom_data(self, data):
            self.beginResetModel()
            self._data = data
            self.endResetModel()
    
    # Main window
    class MainWindow(QMainWindow):
        def __init__(self):
            super().__init__()
            self.resize(800, 480)
    
            # Set widgets
            treeview = QTreeView()
            treemodel = TreeModel()
            treeview.setModel(treemodel)
    
            # Build items
            item1 = MyItem("Item 1", "Item 1 title")
            item1.add_param(MyItemParam('key1', 'value1'))
            item1.add_param(MyItemParam('key2', 'value2'))
            item1.add_param(MyItemParam('key3', 'value3'))
            item2 = MyItem("Item 2", "Item 2 title")
            item2.add_param(MyItemParam('key4', 'value4'))
            item2.add_param(MyItemParam('key5', 'value5'))
            item2.add_param(MyItemParam('key6', 'value6'))
            item3 = MyItem("Item 3", "Item 3 title")
            item3.add_param(MyItemParam('key7', 'value7'))
            item3.add_param(MyItemParam('key8', 'value8'))
            item3.add_param(MyItemParam('key9', 'value9'))
    
            # Load data to the model
            treemodel.load_custom_data([item1, item2, item3])
    
            self.setCentralWidget(treeview)
            self.show()
    
    if __name__ == '__main__':
        app = QApplication(sys.argv)
        widget = MainWindow()
        sys.exit(app.exec())
    
    
    T 1 Reply Last reply 23 Feb 2023, 17:31
    0
    • S Offline
      S Offline
      SGaist
      Lifetime Qt Champion
      wrote on 23 Feb 2023, 20:34 last edited by
      #3

      Hi,

      The Simple Tree Model example should help you get started.

      Interested in AI ? www.idiap.ch
      Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

      1 Reply Last reply
      1
      • T tilz0R
        23 Feb 2023, 17:04

        I have a QTreeView and would like to develop custom model. In the final usage, I'm using SQLite to get table, and then with one-to-many relationship, to display its parameters at second level.

        For first tests, I have 2 classes: MyItem and MyItemParam, that both provide data to display. First one also holds array of second one (one MyItem has many MyItemParam classes).

        This is the direct example I made. I'm obviously struggling to get the correct data. I think main failure I have is around parent and index methods.

        Is there a good example to build custom model? I simply do not like to use QStandardItemModel for each of the line. I'd rather provide data as one big source, and then use model, to construct necessary tree.

        You can run the script directly. PySide 6.4.2 was used for the tests.

        What I want:
        247d9010-c90a-4316-8b1d-4fd8f7437b09-image.png

        import sys
        from PySide6.QtWidgets import *
        from PySide6.QtCore import *
        from PySide6.QtUiTools import *
        
        # Item object with name, title and parameters
        class MyItem():
            def __init__(self, name, title):
                self.name = name
                self.title = title
                self.params = []
        
            def add_param(self, param):
                self.params.append(param)
        
        # MyItemParam with key and value
        class MyItemParam():
            def __init__(self, key, value):
                self.key = key
                self.value = value
        
        # Treeview model
        class TreeModel(QAbstractItemModel):
            def __init__(self):
                super().__init__()
                self._data = []
        
            # Columns and rows
            def columnCount(self, parent):  return 2
            def rowCount(self, parent):     
                if parent.isValid():
                    item = parent.internalPointer()
                    if isinstance(item, MyItem):
                        return len(item.params)
                    else:
                        return 0
                return len(self._data)
        
            # Index creation
            def index(self, row, column, parent = QModelIndex()):
                if parent.isValid():
                    item = parent.internalPointer()
                    if isinstance(item, MyItem):
                        item = item.params[row]
                else:
                    item = self._data[row]
                return self.createIndex(row, column, item)
        
            # Parent object
            def parent(self, index):
                if not index.isValid():
                    return QModelIndex()
                item = index.internalPointer()
                return self.createIndex(index.row(), index.column(), item)
                
            # Get data
            def data(self, index, role):
                item = index.internalPointer()
                if role == Qt.ItemDataRole.DisplayRole:
                    column = index.column()
                    # Print Item data
                    if isinstance(item, MyItem):
                        if column == 0:
                            return item.name
                        elif column == 1:
                            return item.title
                    # Print param data
                    elif isinstance(item, MyItemParam):
                        if column == 0:
                            return item.key
                        elif column == 1:
                            return item.value
                return None
        
            # Add data to the model
            def load_custom_data(self, data):
                self.beginResetModel()
                self._data = data
                self.endResetModel()
        
        # Main window
        class MainWindow(QMainWindow):
            def __init__(self):
                super().__init__()
                self.resize(800, 480)
        
                # Set widgets
                treeview = QTreeView()
                treemodel = TreeModel()
                treeview.setModel(treemodel)
        
                # Build items
                item1 = MyItem("Item 1", "Item 1 title")
                item1.add_param(MyItemParam('key1', 'value1'))
                item1.add_param(MyItemParam('key2', 'value2'))
                item1.add_param(MyItemParam('key3', 'value3'))
                item2 = MyItem("Item 2", "Item 2 title")
                item2.add_param(MyItemParam('key4', 'value4'))
                item2.add_param(MyItemParam('key5', 'value5'))
                item2.add_param(MyItemParam('key6', 'value6'))
                item3 = MyItem("Item 3", "Item 3 title")
                item3.add_param(MyItemParam('key7', 'value7'))
                item3.add_param(MyItemParam('key8', 'value8'))
                item3.add_param(MyItemParam('key9', 'value9'))
        
                # Load data to the model
                treemodel.load_custom_data([item1, item2, item3])
        
                self.setCentralWidget(treeview)
                self.show()
        
        if __name__ == '__main__':
            app = QApplication(sys.argv)
            widget = MainWindow()
            sys.exit(app.exec())
        
        
        T Offline
        T Offline
        tilz0R
        wrote on 23 Feb 2023, 17:31 last edited by tilz0R
        #2

        Let me emphasize that the issue is with actual tree. First level is well displayed.

        1 Reply Last reply
        0
        • S Offline
          S Offline
          SGaist
          Lifetime Qt Champion
          wrote on 23 Feb 2023, 20:34 last edited by
          #3

          Hi,

          The Simple Tree Model example should help you get started.

          Interested in AI ? www.idiap.ch
          Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

          1 Reply Last reply
          1
          • T tilz0R has marked this topic as solved on 24 Feb 2023, 17:14

          1/3

          23 Feb 2023, 17:04

          • Login

          • Login or register to search.
          1 out of 3
          • First post
            1/3
            Last post
          0
          • Categories
          • Recent
          • Tags
          • Popular
          • Users
          • Groups
          • Search
          • Get Qt Extensions
          • Unsolved