2014-03-25 43 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的所有方法和函數的訪問權限。 –