<>一、简述

QTableWidget是我们经常用到的控件。因为Table可以很清晰得展示数据,操作数据,所以在使用过程中我们需要对table进行很多设置来满足我们的需求,table其实是多个控件的组合,比如有横向表头、纵向表头、滚动条、中间表格等。

Table的样式、设置接口很多,详情可以参见Qt助手中介绍。很详细。这里介绍如何在Table表头上添加自定义CheckBox。

<>二、代码之路

代码很简单,重写QHeaderView类,然后设置到对应的Table中即可。

<>重写QHeaderView类
class CheckBoxHeaderView : public QHeaderView { Q_OBJECT public:
CheckBoxHeaderView(int checkColumnIndex, Qt::Orientation orientation, QWidget *
parent = 0) : QHeaderView(orientation, parent) { // 默认ComboBox; m_comboBox =
new QComboBox(this); m_comboBox->addItems(QStringList() << "123" << "456" <<
"789"); } // 获取当前comboBox文字; QString getCurrentComboBoxText() { return
m_comboBox->currentText(); } // 设置自定义ComboBox; void
setComboBoxObject(QComboBox* object) { m_comboBox = object;
m_comboBox->setParent(this); } protected: void paintSection(QPainter *painter,
const QRect &rect, int logicalIndex) const { if (logicalIndex == 0) {
m_comboBox->setGeometry(rect); } else { QHeaderView::paintSection(painter,
rect, logicalIndex); } } private: QComboBox * m_comboBox; };
<>简单测试
class MyTableWidgetWidthComboBox : public QTableWidget { Q_OBJECT public:
MyTableWidgetWidthComboBox(QWidget *parent = Q_NULLPTR); private:
CheckBoxHeaderView * m_checkBoxHeaderView; };
MyTableWidgetWidthComboBox::MyTableWidgetWidthComboBox(QWidget *parent) :
QTableWidget(parent) { this->setAlternatingRowColors(true);
this->setColumnCount(3);
this->setSelectionMode(QAbstractItemView::SingleSelection);
this->setEditTriggers(QAbstractItemView::NoEditTriggers);
this->setSelectionBehavior(QAbstractItemView::SelectRows); // 自定义表头
m_checkBoxHeaderView = new CheckBoxHeaderView(0, Qt::Horizontal, this); //
自定义ComboBox; QComboBox* comboBox = new QComboBox;
comboBox->addItems(QStringList() << "abc" << "def" << "789");
m_checkBoxHeaderView->setComboBoxObject(comboBox); // 设置表头;
this->setHorizontalHeader(m_checkBoxHeaderView);
this->setHorizontalHeaderLabels(QStringList() << "1" << "2" << "3"); }
<>效果图

技术
今日推荐
PPT
阅读数 107
下载桌面版
GitHub
百度网盘(提取码:draw)
Gitee
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:766591547
关注微信