简介
Qt中原生的ComboBox控件的下拉选项是没有鼠标悬停提示(ToolTip)功能,那么想要实现提示功能,就需要对控件进行加工,可以通过重写代理类(QStyledItemDelegate)来实现功能
效果图
实现
非常简单,自定义代理类,继承QStyledItemDelegate,重写helpEvent
函数。
头文件
class ComboBoxTipDelegate : public QStyledItemDelegate
{
Q_OBJECT
public:
ComboBoxTipDelegate(const QMap<QString,QString> _maps,QObject* parent = nullptr);
protected:
virtual bool helpEvent(QHelpEvent *event, QAbstractItemView *view,
const QStyleOptionViewItem &option, const QModelIndex &index) override;
QMap<QString,QString> m_tips; //保存下拉框中显示的文本和对应需要显示的提示
};
源文件:
ComboBoxTipDelegate::ComboBoxTipDelegate(const QMap<QString, QString> _maps, QObject *parent)
: QStyledItemDelegate(parent),m_tips(_maps)
{
}
bool ComboBoxTipDelegate::helpEvent(QHelpEvent *event, QAbstractItemView *view, const QStyleOptionViewItem &option, const QModelIndex &index)
{
QString _text = index.data().toString();
switch (event->type()) {
case QHelpEvent::ToolTip:
if(m_tips.contains(_text))
{
QToolTip::showText(event->globalPos(),m_tips.value(_text));
return true;
}
break;
default:
break;
}
return QStyledItemDelegate::helpEvent(event,view,option,index);
}
使用
QComboBox* box = new QComboBox(widget);
QStringList _temp = {"1","2","3"};
box->addItems(_temp);
QMap<QString,QString> _tempMap = {{"1","提示1"},{"2","提示2"}};
ComboBoxTipDelegate *_delegate = new ComboBoxTipDelegate(_tempMap,box);
box->setItemDelegate(_delegate);