QT4.8-对QLineEdit执行高亮显示

QT4.8 - Implement highlight to QLineEdit

本文关键字:高亮 显示 执行 QLineEdit QT4      更新时间:2023-10-16

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

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

类似于以下内容:${MY_ENVVAR}/foo/bar/myfile

实际上,我想要一个类似于QHighligher课程的东西。

  1. QSyntaxHighliger 子类

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

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

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

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

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

文本编辑.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::Highlighter(QTextDocument *parent)
    : QSyntaxHighlighter(parent)
{
}