Python Forum
[PyQt] Help: check content of combobox in horizontal header of QTableWidget
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[PyQt] Help: check content of combobox in horizontal header of QTableWidget
#1
Hi,

I need to check the content of a combobox header in a QTableWidget.
I found some snippets of code which I used to set up the table with the different comboboxes in the header of a QTableWidget but now I want to know what the selection (e.g. text/index) of the combobox is when I change it. How can I achieve this?

The code so far is presented below:

from PySide2 import QtCore, QtWidgets
import numpy as np

class HorizontalHeader(QtWidgets.QHeaderView):
    def __init__(self, values, parent=None):
        super(HorizontalHeader, self).__init__(QtCore.Qt.Horizontal, parent)
        self.setSectionsMovable(True)
        self.comboboxes = []
        self.sectionResized.connect(self.handleSectionResized)
        self.sectionMoved.connect(self.handleSectionMoved)

    def showEvent(self, event):
        for i in range(2, self.count()):
            if i < len(self.comboboxes):
                combo = self.comboboxes[i]
                combo.clear()
                combo.addItems(["A", "B", 'L', 'T', 'V'])
            else:
                combo = QtWidgets.QComboBox(self)
                combo.addItems(["A", "B", 'L', 'T', 'V'])
                self.comboboxes.append(combo)

            combo.setGeometry(self.sectionViewportPosition(i), 0, self.sectionSize(i)-4, self.height())
            combo.show()

        if len(self.comboboxes) > self.count():
            for i in range(self.count(), len(self.comboboxes)):
                self.comboboxes[i].deleteLater()

        super(HorizontalHeader, self).showEvent(event)

    def handleSectionResized(self, i):
        for i in range(self.count()):
            j = self.visualIndex(i)
            logical = self.logicalIndex(j)
            self.comboboxes[i].setGeometry(self.sectionViewportPosition(logical), 0, self.sectionSize(logical)-4, self.height())

    def handleSectionMoved(self, i, oldVisualIndex, newVisualIndex):
        for i in range(min(oldVisualIndex, newVisualIndex), self.count()):
            logical = self.logicalIndex(i)
            self.comboboxes[i].setGeometry(self.ectionViewportPosition(logical), 0, self.sectionSize(logical) - 5, height())

    def fixComboPositions(self):
        for i in range(self.count()):
            self.comboboxes[i].setGeometry(self.sectionViewportPosition(i), 0, self.sectionSize(i) - 5, self.height())

class TableWidget(QtWidgets.QTableWidget):
    def __init__(self, columns, *args, **kwargs):
        super(TableWidget, self).__init__(*args, **kwargs)
        header = HorizontalHeader(self)


        self.setRowCount(100)
        self.setHorizontalHeader(header)
        # self.setRowCount(rows)
        self.setColumnCount(columns)
        self.setHorizontalHeaderLabels(['Loadcase', 'Step'])
        self.columns = columns
        self.createTable()

    def createTable(self):
        start = 0

        for loadcase in range(10):
            steps = np.random.randint(1, 5)
            end = start + steps

            print(loadcase, steps, start, end)

            for row in range(start, end):
                item = QtWidgets.QTableWidgetItem(str(loadcase + 1))
                item.setFlags(QtCore.Qt.ItemIsUserCheckable |
                              QtCore.Qt.ItemIsEnabled)
                item.setCheckState(QtCore.Qt.Unchecked)
                self.setItem(row, 0, item)
            step = 0

            for row in range(start, end):
                step += 1
                item = QtWidgets.QTableWidgetItem(str(step))
                self.setItem(row, 1, item)

            start = end

        self.data = np.random.rand(end, self.columns-2)

        for i, row_values in enumerate(self.data):
            for j, value in enumerate(row_values):
                self.setItem(i, j+2, QtWidgets.QTableWidgetItem(str(round(value,4))))

        self.itemClicked.connect(self.handleItemClicked)

        self._list = []

    def handleItemClicked(self, item):
        if item.checkState() == QtCore.Qt.Checked:
            if item.row() not in self._list:
                self._list.append(item.row())
            print(self._list)
        else:
            if item.row() in self._list:
                self._list.remove(item.row())
            print(self._list)

    def headerItemClicked(self, logicalIndex):
        column = self.currentItem().column()
        selectedName = self.horizontalHeaderItem(column)
        print(selectedName.text())


    def scrollContentsBy(self, dx, dy):
        super(TableWidget, self).scrollContentsBy(dx, dy)
        if dx != 0:
            self.horizontalHeader().fixComboPositions()


class App(QtWidgets.QWidget):
    def __init__(self):
        super(App,self).__init__()
        self.createTable()
        layout = QtWidgets.QVBoxLayout(self)
        layout.addWidget(self.table)
        self.showMaximized()

    def createTable(self):
        self.table = TableWidget(16)

if __name__ == '__main__':
    import sys

    app = QtWidgets.QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())
Reply
#2
When you create the combo boxes you can connect the "currentIndexChanged" signal to some method in your HorizontalHeader class (def handleSectionIndexChanged?) If you need to expose that to your TableWidget, HorizonalHeader can provide a signal to notify the table when a header selection changes.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tkinter] Horizontal extension of widgets + frame size adapted to content Fab117 3 333 Feb-22-2024, 06:54 PM
Last Post: deanhystad
  [PyQt] QTableWidget print problem JokerSob 8 4,655 Jan-28-2022, 06:08 PM
Last Post: Axel_Erfurt
  [PyQt] How can I sync Combobox index to other combobox index? nickzsche 2 2,329 Jan-03-2022, 12:29 PM
Last Post: Axel_Erfurt
  [PyQt] How do I display the DB table I will choose from the QComboBox in QTableWidget JokerSob 2 2,271 Aug-05-2021, 03:00 PM
Last Post: JokerSob
  Displaying database info in QTableWidget thewolf 6 5,155 Apr-03-2021, 02:49 PM
Last Post: thewolf
  [PyQt] Add validation (regex) to QTableWidget cells mart79 0 2,688 May-05-2020, 12:51 PM
Last Post: mart79
  [PyQt] QTableWidget stylesheet error mart79 3 6,311 Feb-26-2020, 04:54 PM
Last Post: Denni
  [PyQt] Pyqt5: How do you make a button that adds new row with data to a Qtablewidget YoshikageKira 6 6,873 Jan-02-2020, 04:32 PM
Last Post: Denni
  [Tkinter] Tkinter delete combobox content and not the list LagratteCchouette 4 8,340 Dec-29-2019, 11:04 AM
Last Post: LagratteCchouette
  Require scroll bars horizontal and vertical throughout the window tejgandhi 2 2,675 Jun-28-2019, 03:13 AM
Last Post: tejgandhi

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020