是否可以设置 QTableView 角按钮的文本? [英] Is it possible to set the text of the QTableView corner button?

查看:39
本文介绍了是否可以设置 QTableView 角按钮的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

QTableView 有一个 角按钮,占据了水平和垂直标题之间的交叉点.单击此按钮将选择表中的所有单元格.我想知道是否可以设置此按钮的文本,如果可以,如何设置?

QTableView has a corner button, occupying the intersection between the horizontal and the vertical header. Clicking this will select all cells in the table. What I'm wondering is if it's possible to set this button's text, and if so, how?

推荐答案

我已经用 PyQt 5.3 实现了一个可行的解决方案,而且它只用了很少的代码.我的解决方案基于 this question 中发布的代码Qt 中心.

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

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

这篇关于是否可以设置 QTableView 角按钮的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆