QT 表格设置左上角按钮

来源:互联网 发布:ps4重新构建数据库 编辑:程序博客网 时间:2024/05/22 08:10

 QT表格模型没有提供访问左上角按钮的API, 查看qtableview.cpp 发现其中有一个QTableCornerButton的私有类, 既然AP没有暴露出该类, 那我们如何设置左上角按钮的显示方式呢?

 

一. 设置左上角按钮背景色

      既然知道左上角按钮就是QTableCornerButton, 我们就可以通过该类名设置该按钮样式 

Cpp代码  收藏代码
  1. table->setStyleSheet("QTableCornerButton::section{background-color:red;}");  

 

二. 设置按钮文本

    虽然没有提供直接的访问方式,可以通过findChild()来定位到该按钮,然后设置其文本及显示宽度.

Cpp代码  收藏代码
  1. class TableWidget:public QTableWidget  
  2. {  
  3. public:  
  4.     TableWidget(int rows, int cols, QWidget* parent = 0)  
  5.         : QTableWidget(rows, cols, parent)  
  6.     {  
  7.         QAbstractButton* btn = findChild<QAbstractButton*>();  
  8.         if (btn)  
  9.         {  
  10.             btn->setText("Text");  
  11.             btn->installEventFilter(this);  
  12.   
  13.             // adjust the width of the vertical header to match the preferred corner button width  
  14.   
  15.             // (unfortunately QAbstractButton doesn't implement any size hinting functionality)  
  16.   
  17.             QStyleOptionHeader opt;  
  18.             opt.text = btn->text();  
  19.             QSize s = (btn->style()->sizeFromContents(QStyle::CT_HeaderSection, &opt, QSize(), btn).  
  20.                        expandedTo(QApplication::globalStrut()));  
  21.             if (s.isValid())  
  22.                 verticalHeader()->setMinimumWidth(s.width());  
  23.         }  
  24.     }  
  25.   
  26.     bool eventFilter(QObject* o, QEvent* e)  
  27.     {  
  28.         if (e->type() == QEvent::Paint)  
  29.         {  
  30.             QAbstractButton* btn = qobject_cast<QAbstractButton*>(o);  
  31.             if (btn)  
  32.             {  
  33.                 // paint by hand (borrowed from QTableCornerButton)  
  34.   
  35.                 QStyleOptionHeader opt;  
  36.                 opt.init(btn);  
  37.                 QStyle::State state = QStyle::State_None;  
  38.                 if (btn->isEnabled())  
  39.                     state |= QStyle::State_Enabled;  
  40.                 if (btn->isActiveWindow())  
  41.                     state |= QStyle::State_Active;  
  42.                 if (btn->isDown())  
  43.                     state |= QStyle::State_Sunken;  
  44.                 opt.state = state;  
  45.                 opt.rect = btn->rect();  
  46.                 opt.text = btn->text(); // this line is the only difference to QTableCornerButton  
  47.   
  48.                 opt.position = QStyleOptionHeader::OnlyOneSection;  
  49.                 QStylePainter painter(btn);  
  50.                 painter.drawControl(QStyle::CE_Header, opt);  
  51.                 return true// eat event  
  52.   
  53.             }  
  54.         }  
  55.         return false;  
  56.     }  
  57. };  

  

    运行效果:

    运行效果



文章 来源:http://tcspecial.iteye.com/blog/1923063

0 0