zoukankan      html  css  js  c++  java
  • QObject就有eventFilter,功能很强(随心所欲的进行处理,比如用来QLineEdit分词)

    相信大家都用过词典吧!因为英语不太好。。。O(∩_∩)O~,所以经常进行划词翻译!

    实现

    原理:鼠标移至某单词之上,获取鼠标位置,然后在对应位置进行取词,翻译!

    基于此原理,下面我们实现为每一个单词显示QToolTip。

    效果

    这里写图片描述

    源码

    创建QTextEdit队形,然后通过installEventFilter进行事件监听。

    m_pTextEdit = new QTextEdit(this);
    m_pTextEdit->setObjectName("highlightLabel");
    m_pTextEdit->append(QString::fromLocal8Bit("一去丶二三里"));
    m_pTextEdit->append(QString::fromLocal8Bit("青春不老,奋斗不止!"));
    m_pTextEdit->append(QString::fromLocal8Bit("You are not alone."));
    m_pTextEdit->append(QString::fromLocal8Bit("进步始于交流,收获源于分享。"));
    
    // 安装事件过滤器
    m_pTextEdit->installEventFilter(this);

    实现eventFilter,判断事件类型为QEvent::ToolTip时,获取光标,进行取词。

    bool MainWindow::eventFilter(QObject *obj, QEvent *event)
    {
        if (obj == m_pTextEdit)
        {
            // 事件为提示
            if (event->type() == QEvent::ToolTip)
            {
                QHelpEvent *pHelpEvent = static_cast<QHelpEvent *>(event);
    
                // 获取光标
                QTextCursor cursor = m_pTextEdit->cursorForPosition(pHelpEvent->pos());
                cursor.select(QTextCursor::WordUnderCursor); // 真正分词
    
                // 显示提示信息
                QToolTip::showText(pHelpEvent->globalPos(), cursor.selectedText()); 
    
                return true;
            }
        }
        return QDialog::eventFilter(obj, event);
    }

    如果对事件过滤不熟悉,可查看更多参考。

    http://blog.csdn.net/liang19890820/article/details/51804098

  • 相关阅读:
    Android P Beta发布!最新版本抢先体验!
    手游热更新方案--Unity3D下的CsToLua技术
    2018 Unite大会——《使用UPA工具优化项目》演讲实录
    浅谈软件工程师的代码素养
    Android平台的Swift—Kotlin
    1计算机的基本组成-3
    1计算机的基本组成-2
    新的公司
    4 对象的行为 方法操作实例变量
    反射机制
  • 原文地址:https://www.cnblogs.com/findumars/p/5702119.html
Copyright © 2011-2022 走看看