QComboBox使用代理设置鼠标悬停提示

简介

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);
  • 11
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值