Qt view to display data columns vertically in pairs

204 Views Asked by At

I’m currently wrapping my mind around model/view programming using Qt via PySide6 in Python. I’m looking for a view that supports displaying the column data of data rows vertically in pairs (for simplification I’m only assuming 2 columns here, A and B). To illustrate this, in a QTableView, data would be displayed like this (for columns A and B):

A B
A B

While I want it to display like this:

A
B

A
B

Could someone point me to a good starting point to achieve this? I initially played around with displaying data using QDataWidgetMapper for widgets within a QScrollArea, but this doesn’t feel like the right way to do it.

1

There are 1 best solutions below

0
Andre Jonas On

Here’s what I came up with based on Remarkod’s suggestion to use QTreeView. This leaves some space between the pairs of data, but that’s fine for me. I guess it would be possible to completely hide the root items somehow, instead of just leaving them empty and unselectable.

import sys

from PySide6.QtGui import QStandardItem, QStandardItemModel, Qt
from PySide6.QtWidgets import QApplication, QMainWindow, QTreeView


class RootItem(QStandardItem):
    def __init__(self):
        super().__init__()

        # Make root items unselectable
        self.setEditable(False)
        self.setFlags(Qt.NoItemFlags)


class ItemA(QStandardItem):
    def __init__(self):
        super().__init__()

        self.setText("A")


class ItemB(QStandardItem):
    def __init__(self):
        super().__init__()

        self.setText("B")


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.treeModel = QStandardItemModel()
        self.rootNode = self.treeModel.invisibleRootItem()

        self.treeView = QTreeView()
        self.treeView.setHeaderHidden(True)
        self.treeView.setModel(self.treeModel)

        rootItem_1 = RootItem()
        item_a1 = ItemA()
        item_b1 = ItemB()

        rootItem_2 = RootItem()
        item_a2 = ItemA()
        item_b2 = ItemB()

        rootItem_1.appendRow(item_a1)
        rootItem_1.appendRow(item_b1)
        self.rootNode.appendRow(rootItem_1)

        rootItem_2.appendRow(item_a2)
        rootItem_2.appendRow(item_b2)
        self.rootNode.appendRow(rootItem_2)

        # Expand all items, make them unexpandable, and hide decoration for root items
        self.treeView.setItemsExpandable(False)
        self.treeView.setRootIsDecorated(False)
        self.treeView.expandAll()

        self.setCentralWidget(self.treeView)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    main_win = MainWindow()
    main_win.show()
    sys.exit(app.exec())