QT4.8 - 为QLineEdit实现高亮显示

时间:2014-09-08 02:41:50

标签: c++ qt

我正在寻找一种为QLineEdit小部件实现荧光笔的方法。

我正在使用QLineEdit在我的应用程序中存储一个路径变量,我想突出显示环境变量。

这样的事情: 的 $ {MY_ENVVAR} /富/酒吧/ MYFILE

实际上我会有类似QHightligher类的东西。

1 个答案:

答案 0 :(得分:1)

  1. 子类QSyntaxHighliger

  2. 编写您自己的highlightBlock()方法

  3. 在字符串中检测必须着色的特定文本(例如,可以通过正则表达式QRegExp执行此操作)并使用setFormat()方法将字符串从x绘制到x + n用一些颜色

  4. 有用的链接:http://qt-project.org/doc/qt-4.8/qsyntaxhighlighter.html#highlightBlock

    我以前从未使用过QLineEdit的高亮度,所以这是不可能的。但我们可以简单地将高亮度附加到QTextEdit。所以我们应该从textEdit创建lineEdit,web中有很多例子如何做到这一点。

    例如(我使用hyde给出的代码添加少量代码。)

    TextEdit.h

    #ifndef TEXTEDIT_H
    #define TEXTEDIT_H
    
    #include <QTextEdit>
    #include <QCompleter>
    
    #include <QTextEdit>
    #include <QKeyEvent>
    #include <QStyleOption>
    #include <QApplication>
    
    
    class TextEdit : public QTextEdit
    {
        Q_OBJECT
    public:
            explicit TextEdit(QWidget *parent = 0)
            {
                    setTabChangesFocus(true);
                    setWordWrapMode(QTextOption::NoWrap);
                    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
                    setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
                    setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
                    setFixedHeight(sizeHint().height());
            }
    
        void keyPressEvent(QKeyEvent *event)
    
        {
    
                if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter)
    
                        event->ignore();
    
                else
    
                        QTextEdit::keyPressEvent(event);
    
        }
            QSize sizeHint() const
            {
                    QFontMetrics fm(font());
                    int h = qMax(fm.height(), 14) + 4;
                    int w = fm.width(QLatin1Char('x')) * 17 + 4;
                    QStyleOptionFrameV2 opt;
                    opt.initFrom(this);
                    return (style()->sizeFromContents(QStyle::CT_LineEdit, &opt, QSize(w, h).
                            expandedTo(QApplication::globalStrut()), this));
            }
    };
    
    #endif // TEXTEDIT_H
    

    用法(在main.cpp中)

    #include "textedit.h"
    
    //...
    
        TextEdit *t = new TextEdit;
        t->show();
        new Highlighter(t->document());
    

    荧光笔构造函数为例

    Highlighter::Highlighter(QTextDocument *parent)
        : QSyntaxHighlighter(parent)
    
    {
    
    }