关于
网上的方法基本上都是采用重写QHeaderVIew,然后通过HeaderView::paintSection来实现。这种实现方法很僵硬。
不仅实现起来麻烦,代码过于底层容易出错,而且通过重写mouseEvent设置flag来判断是否check,实际体验比较慢,比原生checkBox反应慢很多,体验不佳。
资料
我参考了一下Qt写的DB Browser (SQLite)这个软件,它在表头添加了个QLineEdit作为filter。
这是它的界面:
实现方法就是通过重写QHeaderVIew,在QAbstractItemView::updateGeometries()函数中设置位置就行了。
实现效果:
代码:
class HeaderViewPrivate : public QHeaderView
{
Q_OBJECT
public:
explicit HeaderViewPrivate(Qt::Orientation orientation, QWidget * parent = 0)
: QHeaderView(orientation, parent) {
m_headerCbx = new QCheckBox(this);
m_headerCbx->setVisible(true);
}
protected:
void updateGeometries() {
m_headerCbx->move(sectionPosition(0) + 3, 6);
}
private:
QCheckBox *m_headerCbx;
};
github:
https://github.com/houhaotian/QTableViewDemo.git