Here, at Qt Wiki, 它说没有捷径,你必须自己继承 headerView。
这是该 wiki 答案的摘要:
"目前还没有API可以在header中插入widget,但是你可以自己绘制checkbox以便将它插入到header中。
你可以做的是继承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();
}