在Qt Wiki上提到,目前没有快捷方式可以在表头中插入小部件,您需要自己子类化headerView。
以下是该维基答案的摘要:
“目前没有API可以在表头中插入小部件,但您可以自己绘制复选框以将其插入表头。
您可以子类化QHeaderView,重新实现paintSection(),然后在想要放置此复选框的部分使用PE_IndicatorCheckBox调用drawPrimitive()。
您还需要重新实现mousePressEvent()以检测单击复选框的情况,以便绘制已选和未选状态。
下面的示例说明了如何完成此操作:
#include <QtGui>
class MyHeader : public QHeaderView
{
public:
MyHeader(Qt::Orientation orientation, QWidget * parent = 0) : QHeaderView(orientation, parent)
{}
protected:
void paintSection(QPainter *painter, const QRect &rect, int logicalIndex) const
{
painter->save();
QHeaderView::paintSection(painter, rect, logicalIndex);
painter->restore();
if (logicalIndex == 0)
{
QStyleOptionButton option;
option.rect = QRect(10,10,10,10);
if (isOn)
option.state = QStyle::State_On;
else
option.state = QStyle::State_Off;
this->style()->drawPrimitive(QStyle::PE_IndicatorCheckBox, &option, painter);
}
}
void mousePressEvent(QMouseEvent *event)
{
if (isOn)
isOn = false;
else
isOn = true;
this->update();
QHeaderView::mousePressEvent(event);
}
private:
bool isOn;
};
int main(int argc, char **argv)
{
QApplication app(argc, argv);
QTableWidget table;
table.setRowCount(4);
table.setColumnCount(3);
MyHeader *myHeader = new MyHeader(Qt::Horizontal, &table);
table.setHorizontalHeader(myHeader);
table.show();
return app.exec();
}