QT表格模型没有提供访问左上角按钮的API, 查看qtableview.cpp 发现其中有一个QTableCornerButton的私有类, 既然AP没有暴露出该类, 那我们如何设置左上角按钮的显示方式呢?
一. 设置左上角按钮背景色
既然知道左上角按钮就是QTableCornerButton, 我们就可以通过该类名设置该按钮样式
- table->setStyleSheet("QTableCornerButton::section{background-color:red;}");
二. 设置按钮文本
虽然没有提供直接的访问方式,可以通过findChild()来定位到该按钮,然后设置其文本及显示宽度.
- class TableWidget:public QTableWidget
- {
- public:
- TableWidget(int rows, int cols, QWidget* parent = 0)
- : QTableWidget(rows, cols, parent)
- {
- QAbstractButton* btn = findChild<QAbstractButton*>();
- if (btn)
- {
- btn->setText("Text");
- btn->installEventFilter(this);
- // adjust the width of the vertical header to match the preferred corner button width
- // (unfortunately QAbstractButton doesn't implement any size hinting functionality)
- QStyleOptionHeader opt;
- opt.text = btn->text();
- QSize s = (btn->style()->sizeFromContents(QStyle::CT_HeaderSection, &opt, QSize(), btn).
- expandedTo(QApplication::globalStrut()));
- if (s.isValid())
- verticalHeader()->setMinimumWidth(s.width());
- }
- }
- bool eventFilter(QObject* o, QEvent* e)
- {
- if (e->type() == QEvent::Paint)
- {
- QAbstractButton* btn = qobject_cast<QAbstractButton*>(o);
- if (btn)
- {
- // paint by hand (borrowed from QTableCornerButton)
- QStyleOptionHeader opt;
- opt.init(btn);
- QStyle::State state = QStyle::State_None;
- if (btn->isEnabled())
- state |= QStyle::State_Enabled;
- if (btn->isActiveWindow())
- state |= QStyle::State_Active;
- if (btn->isDown())
- state |= QStyle::State_Sunken;
- opt.state = state;
- opt.rect = btn->rect();
- opt.text = btn->text(); // this line is the only difference to QTableCornerButton
- opt.position = QStyleOptionHeader::OnlyOneSection;
- QStylePainter painter(btn);
- painter.drawControl(QStyle::CE_Header, opt);
- return true; // eat event
- }
- }
- return false;
- }
- };
运行效果:
文章 来源:http://tcspecial.iteye.com/blog/1923063