Skip to content Skip to sidebar Skip to footer

Get Correct Parent In A Slot Triggered By Button Inside A Qheaderview Class

Just for a sport of it I am playing around with a demo code from @ekhumoro (all credits for original Qt4 code goes to him), where he inserted a new line of QLineEdit widgets into Q

Solution 1:

sender() is a method that indicates to which object the signal belongs, and it is obvious changebuttonsymbol belongs to the header that obviously does not have a text() method. On the other hand, it is better for each class to manage its own objects, so the change of the button text must be implemented in the header.

Finally, if a complex widget is used, it is better to have it in a class.

import sys

from PyQt5.QtCore import pyqtSignal, Qt
from PyQt5.QtGui import QStandardItemModel
from PyQt5.QtWidgets import (
    QHeaderView,
    QWidget,
    QLineEdit,
    QApplication,
    QTableView,
    QVBoxLayout,
    QHBoxLayout,
    QComboBox,
    QPushButton,
    QCheckBox,
)


classWidget(QWidget):
    def__init__(self, parent=None):
        super().__init__(parent)
        self.btn = QPushButton()
        self.btn.setText("=")
        self.btn.setFixedWidth(20)

        self.linee = QLineEdit()
        self.linee.setPlaceholderText("Filter")

        lay = QHBoxLayout(self)
        lay.setContentsMargins(0, 0, 0, 0)
        lay.setSpacing(0)
        lay.addWidget(self.btn)
        lay.addWidget(self.linee)


classFilterHeader(QHeaderView):
    filterActivated = pyqtSignal()

    def__init__(self, parent):
        super().__init__(Qt.Horizontal, parent)
        self._editors = []
        self._padding = 4
        self.setStretchLastSection(True)
        # self.setResizeMode(QHeaderView.Stretch)
        self.setDefaultAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.setSortIndicatorShown(False)
        self.sectionResized.connect(self.adjustPositions)
        parent.horizontalScrollBar().valueChanged.connect(self.adjustPositions)

    defsetFilterBoxes(self, count):
        while self._editors:
            editor = self._editors.pop()
            editor.deleteLater()
        for index inrange(count):
            editor = self.create_editor(self.parent(), index)
            self._editors.append(editor)
        self.adjustPositions()

    defcreate_editor(self, parent, index):
        if index == 1:  # Empty
            editor = QWidget()
        elif index == 2:  # Number filter (>|=|<)
            editor = Widget(parent)
            editor.linee.returnPressed.connect(self.filterActivated)
            editor.btn.clicked.connect(self.changebuttonsymbol)
        elif index == 3:
            editor = QComboBox(parent)
            editor.addItems(["", "Combo", "One", "Two", "Three"])
            editor.currentIndexChanged.connect(self.filterActivated)
        elif index == 4:
            editor = QPushButton(parent)
            editor.clicked.connect(self.filterActivated)
            editor.setText("Button")
        elif index == 5:
            editor = QCheckBox(parent)
            editor.clicked.connect(self.filterActivated)
            editor.setTristate(True)
            editor.setCheckState(Qt.Checked)
            editor.setText("CheckBox")
        else:
            editor = QLineEdit(parent)
            editor.setPlaceholderText("Filter")
            editor.returnPressed.connect(self.filterActivated)
        return editor

    defsizeHint(self):
        size = super().sizeHint()
        if self._editors:
            height = self._editors[0].sizeHint().height()
            size.setHeight(size.height() + height + self._padding)
        return size

    defupdateGeometries(self):
        if self._editors:
            height = self._editors[0].sizeHint().height()
            self.setViewportMargins(0, 0, 0, height + self._padding)
        else:
            self.setViewportMargins(0, 0, 0, 0)
        super().updateGeometries()
        self.adjustPositions()

    defadjustPositions(self):
        for index, editor inenumerate(self._editors):
            ifnotisinstance(editor, QWidget):
                continue
            height = editor.sizeHint().height()
            compensate_y = 0
            compensate_x = 0iftype(editor) is QComboBox:
                compensate_y = +2eliftype(editor) in (QWidget, Widget):
                compensate_y = -1eliftype(editor) is QPushButton:
                compensate_y = -1eliftype(editor) is QCheckBox:
                compensate_y = 4
                compensate_x = 4
            editor.move(
                self.sectionPosition(index) - self.offset() + 1 + compensate_x,
                height + (self._padding // 2) + 2 + compensate_y,
            )
            editor.resize(self.sectionSize(index), height)

    deffilterText(self, index):
        for editor in self._editors:
            ifhasattr(editor, "text") andcallable(editor.text):
                return editor.text()
        return""defsetFilterText(self, index, text):
        for editor in self._editors:
            ifhasattr(editor, "setText") andcallable(editor.setText):
                editor.setText(text)

    defclearFilters(self):
        for editor in self._editors:
            editor.clear()

    defchangebuttonsymbol(self):
        nbtn = self.sender()
        if nbtn.text() == "=":
            nbtn.setText(">")
        elif nbtn.text() == ">":
            nbtn.setText("<")
        else:
            nbtn.setText("=")


classWindow(QWidget):
    def__init__(self):
        super(Window, self).__init__()
        self.view = QTableView()
        layout = QVBoxLayout(self)
        layout.addWidget(self.view)
        header = FilterHeader(self.view)
        self.view.setHorizontalHeader(header)
        model = QStandardItemModel(self.view)
        model.setHorizontalHeaderLabels("One Two Three Four Five Six Seven".split())
        self.view.setModel(model)
        header.setFilterBoxes(model.columnCount())
        header.filterActivated.connect(self.handleFilterActivated)

    defhandleFilterActivated(self):
        header = self.view.horizontalHeader()
        for index inrange(header.count()):
            if index != 4:
                print(index, header.filterText(index))
            else:
                print("Button")


if __name__ == "__main__":

    app = QApplication(sys.argv)
    window = Window()
    window.setGeometry(800, 100, 600, 300)
    window.show()
    sys.exit(app.exec_())

Post a Comment for "Get Correct Parent In A Slot Triggered By Button Inside A Qheaderview Class"