QT C++实现表头添加组件
QTableWidget在表头添加组件
QTableWidget的表头有一个类QHeaderView是专门处理表头的类,要在表头添加一个类似QCheckBox的组件需要重写一个类并继承QHeaderView。
QTableWidget中添加复选框并实现全选居中:
- 自定义类MyHeaderView并继承QHeaderView
- 自定义类MyTableWidget并继承QTableWidget
myheaderview.h
#ifndef MYHEADERVIEW_H
#define MYHEADERVIEW_H
#include <QHeaderView>
#include <Qt>
class MyHeaderView : public QHeaderView
{
//Q_OBJECT:使用信号和槽函数必备的宏
public:
struct Margins
{
int left;
int right;
int top;
int buttom;
Margins(int left = 2, int right = 2, int top = 2, int buttom = 2); //通过构造函数设置默认参数
};
explicit MyHeaderView(Qt::Orientation orientation, QWidget *parent = nullptr);
~MyHeaderView();
void SetItemWidget(int index, QWidget * widget); //表头添加组件,比如checkbox、pushbutton
void SetItemMargins(int index, Margins margins); //设置边距
private:
struct Item
{
QWidget * item; //组件
Margins margins; //边缘
Item(); //默认构造函数
};
QMap<int, Item> mItems; //<key, data>
};
#endif // MYHEADERVIEW_H
myheaderview.cpp
#include "myheaderview.h"
MyHeaderView::MyHeaderView(Qt::Orientation orientation, QWidget * parent)
: QHeaderView(orientation, parent)
{
}
MyHeaderView::~MyHeaderView()
{
}
void MyHeaderView::SetItemWidget(int index, QWidget *widget)
{
widget->setParent(this);
mItems[index].item = widget;
}
void MyHeaderView::SetItemMargins(int index, Margins margins)
{
mItems[index].margins = margins;
}
MyHeaderView::Item::Item() : item(nullptr)
{
}
MyHeaderView::Margins::Margins(int left, int right, int top, int buttom) :
left(left),
right(right),
top(top),
buttom(buttom)
{
}
mytablewidget.h
#ifndef MYTABLEWIDGET_H
#define MYTABLEWIDGET_H
#include <QTableWidget>
#include "myheaderview.h"
class MyTableWidget : public QTableWidget
{
//Q_OBJECT
public:
MyTableWidget(QWidget * parent = nullptr);
~MyTableWidget();
void SetHorizontalHeaderItemWidget(int column, QWidget * widget); //表头添加组件
void SetHorizontalHeaderItemMargins(int column, MyHeaderView::Margins margins); //修改表头组件的边距
private:
MyHeaderView *myheadview;
};
#endif // MYTABLEWIDGET_H
mytablewidget.cpp
#include "mytablewidget.h"
MyTableWidget::MyTableWidget(QWidget * parent)
: QTableWidget(parent)
{
myheadview = new MyHeaderView(Qt::Orientation::Horizontal, this);
setHorizontalHeader(myheadview); //这里有upcasting
}
MyTableWidget::~MyTableWidget()
{
delete myheadview;
}
void MyTableWidget::SetHorizontalHeaderItemWidget(int column, QWidget *widget)
{
myheadview->SetItemWidget(column, widget);
}
void MyTableWidget::SetHorizontalHeaderItemMargins(int column, MyHeaderView::Margins margins)
{
myheadview->SetItemMargins(column, margins);
}
使用方法:
table->setColumnCount(5);
QCheckBox all_check = new QCheckBox("全选");
table->SetHorizontalHeaderItemWidget(0, all_check); //在第0列添加一个QCheckBox
效果预览:
参考:https://stackoverflow.com/questions/27000484/add-custom-widgets-as-qtablewidget-horizontalheader