QComboBox代理

ComboBoxDelegate.h文件

#ifndef COMBOBOXDELEGATE_H
#define COMBOBOXDELEGATE_H

#include <QObject>
#include <QStyledItemDelegate>
#include <QComboBox>

class ComboBoxDelegate : public QStyledItemDelegate
{
    Q_OBJECT
public:
	ComboBoxDelegate( QObject *parent = nullptr);

	void setItems(const QStringList &texts);

public:
	QWidget *createEditor(QWidget *parent,
		const QStyleOptionViewItem &option,
		const QModelIndex &index) const override;

	void setEditorData(QWidget *editor, const QModelIndex &index) const override;
	void setModelData(QWidget *editor,
		QAbstractItemModel *model,
		const QModelIndex &index) const override;

	void updateEditorGeometry(QWidget *editor,
		const QStyleOptionViewItem &option,
		const QModelIndex &index) const override;

	void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;

private:
	//下拉框选项
    QStringList _texts;
};

#endif // COMBOBOXDELEGATE_H

ComboBoxDelegate.cpp文件

#include "ComboBoxDelegate.h"

ComboBoxDelegate::ComboBoxDelegate(QObject *parent/*=nullptr*/)
	: QStyledItemDelegate(parent)
{

}
void ComboBoxDelegate::setItems(const QStringList &texts)
{
	_texts = texts;
}

QWidget* ComboBoxDelegate::createEditor(QWidget *parent,
	const QStyleOptionViewItem &option,
	const QModelIndex &index) const
{
	QComboBox *editor = new QComboBox(parent);
	editor->addItems(_texts);
	return editor;
}

void ComboBoxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
	QString text = index.model()->data(index, Qt::EditRole).toString();
	QComboBox *comboBox = static_cast<QComboBox*>(editor);
	int tindex = comboBox->findText(text);
	comboBox->setCurrentIndex(tindex);
}

void ComboBoxDelegate::setModelData(QWidget *editor,
	QAbstractItemModel *model,
	const QModelIndex &index) const
{
	QComboBox *comboBox = static_cast<QComboBox*>(editor);
	QString text = comboBox->currentText();
	model->setData(index, text, Qt::EditRole);
}

void ComboBoxDelegate::updateEditorGeometry(QWidget *editor,
	const QStyleOptionViewItem &option,
	const QModelIndex &index) const
{
	editor->setGeometry(option.rect);
}

void ComboBoxDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
	QStyleOptionViewItem viewOption(option);
	initStyleOption(&viewOption, index);
	QStyledItemDelegate::paint(painter, viewOption, index);
}


使用

	//设置第0列为下拉框代理 
	ComboBoxDelegate* m_cbDlg = new ComboBoxDelegate;
	m_tableWidget->setItemDelegateForColumn(0, m_cbDlg)
	
	QStringList items;
	items << QString("类型1")
		<< QString("类型2")
		<< QString("类型3");

	//设置下拉框选项
	m_cbDlg->setItems(items);

示例工程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值