2014-03-25 46 views
4

QTableView有一个corner button,占用水平和垂直标题之间的交集。点击这个将选择表格中的所有单元格。我想知道的是,如果可以设置这个按钮的文本,如果是这样,怎么样?是否可以设置QTableView角落按钮的文字?

+1

请参阅[在qt中心的这个问题](http://www.qtcentre.org/threads/6252-QTableWidget-NW-corner-header-item)。 – thuga

回答

3

我已经使用PyQt 5.3实现了一个工作解决方案,并且它只用了很少的代码。我的解决方案基于Qt中心的this question中发布的代码。

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 
+0

它为QTableView的cornerButton打开QtWidgets.QAbstractButton的所有方法和函数的访问权限。 –