Qt之QTableWidget 表头添加QComBox

重写QHeaderView

重写HeaderView,然后设置到对应的tablewidget中去。

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");
}




在这里插入图片描述

  • 0
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值