Can I set the text of a QTableView corner button?

QTableView has a corner button, occupying the intersection of horizontal and vertical headers. By clicking on it, select all the cells in the table. I am wondering if this button text can be set, and if so, how?

+4
source share
1 answer

I implemented a working solution with PyQt 5.3, and it took surprisingly little code. My solution is based on the code posted in on this question at the Qt Center.

from PyQt5 import QtWidgets, QtCore


class TableView(QtWidgets.QTableView):
    """QTableView specialization that can e.g. paint the top left corner header.
    """
    def __init__(self, nw_heading, parent):
        super(TableView, self).__init__(parent)

        self.__nw_heading = nw_heading
        btn = self.findChild(QtWidgets.QAbstractButton)
        btn.setText(self.__nw_heading)
        btn.setToolTip('Toggle selecting all table cells')
        btn.installEventFilter(self)

        opt = QtWidgets.QStyleOptionHeader()
        opt.text = btn.text()
        s = QtCore.QSize(btn.style().sizeFromContents(
            QtWidgets.QStyle.CT_HeaderSection, opt, QtCore.QSize(), btn).
            expandedTo(QtWidgets.QApplication.globalStrut()))

        if s.isValid():
            self.verticalHeader().setMinimumWidth(s.width())

    def eventFilter(self, obj, event):
        if event.type() != QtCore.QEvent.Paint or not isinstance(
                obj, QtWidgets.QAbstractButton):
            return False

        # Paint by hand (borrowed from QTableCornerButton)
        opt = QtWidgets.QStyleOptionHeader()
        opt.initFrom(obj)
        styleState = QtWidgets.QStyle.State_None
        if obj.isEnabled():
            styleState |= QtWidgets.QStyle.State_Enabled
        if obj.isActiveWindow():
            styleState |= QtWidgets.QStyle.State_Active
        if obj.isDown():
            styleState |= QtWidgets.QStyle.State_Sunken
        opt.state = styleState
        opt.rect = obj.rect()
        # This line is the only difference to QTableCornerButton
        opt.text = obj.text()
        opt.position = QtWidgets.QStyleOptionHeader.OnlyOneSection
        painter = QtWidgets.QStylePainter(obj)
        painter.drawControl(QtWidgets.QStyle.CE_Header, opt)

        return True
+3
source

Source: https://habr.com/ru/post/1533343/


All Articles