我正在寻找一种为QLineEdit小部件实现荧光笔的方法。
我使用QLineEdit在应用程序中存储路径变量,并突出显示环境变量。
就像这样:${MY_ENVVAR}/foo/bar/myfile
实际上,我会有类似于QHightligher类的东西。
发布于 2014-09-08 04:02:32
QSyntaxHighligerhighlightBlock()方法QRegExp),并使用setFormat()方法将x到x+n的字符串绘制成某种颜色。有用的链接:http://qt-project.org/doc/qt-4.8/qsyntaxhighlighter.html#highlightBlock
我以前从来没有用过高升的QLineEdit,所以这是不可能的。但是我们可以简单地把高升装到QTextEdit上。因此,我们应该从lineEdit中创建textEdit,在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)
{
}https://stackoverflow.com/questions/25716782
复制相似问题