双击表头进入编辑状态,示例:
#include <QHeaderView>
/* 自定义表头 双击可编辑 */
class CusEditableHeaderView : public QHeaderView
{
Q_OBJECT
public:
explicit CusEditableHeaderView(Qt::Orientation orientation, QWidget * parent = 0)
: QHeaderView(orientation, parent) {
//可移动
setSectionsMovable(true);
//最后一列顶边
setStretchLastSection(true);
//编辑框
m_lineEdit = new QLineEdit(this);
//默认隐藏
m_lineEdit->setHidden(true);
connect(this, &QHeaderView::sectionDoubleClicked, this, [&](int logicalIdx){
//双击显示编辑框
m_lineEdit->setHidden(false);
//编辑框大小同当前section
m_lineEdit->resize(sectionSize(logicalIdx),height());
//编辑框移到当前位置
m_lineEdit->move(sectionPosition(logicalIdx), 0);
//获取当前内容
QVariant var = model()->headerData(logicalIdx, Qt::Horizontal);
//填充至编辑框
m_lineEdit->setText(var.toString());
m_curSection = logicalIdx;
/*qDebug() <<CN("逻辑位置(move过后值不变)")<< logicalIdx
<<CN("item从左到右计算的位置") << sectionPosition(logicalIdx)
<< CN("虚拟位置(move过后值改变为新的位置)") << visualIndex(logicalIdx);*/
});
connect(m_lineEdit, &QLineEdit::editingFinished, this, [&](){
m_lineEdit->setHidden(true);
model()->setHeaderData(m_curSection, Qt::Horizontal, m_lineEdit->text());
emit signal_edtFshed(m_lineEdit->text());
});
}
signals:
void signal_edtFshed(QString txt);
private:
QLineEdit *m_lineEdit;
int m_curSection;
};