|
本帖最后由 miroox 于 2018-5-7 19:56 编辑
一个例子
logbox.h
- #ifndef LOGBOX_H
- #define LOGBOX_H
- #include <QWidget>
- class QTextEdit;
- class LogBox : public QWidget
- {
- Q_OBJECT
- public:
- LogBox(QWidget *parent = 0);
- ~LogBox();
- public slots:
- void append(const QString& str);
- private slots:
- void highlightCurrentLine();
- private:
- QTextEdit* edit;
- };
- #endif // LOGBOX_H
复制代码
logbox.cpp
- #include "logbox.h"
- #include <QTextEdit>
- #include <QHBoxLayout>
- LogBox::LogBox(QWidget *parent)
- : QWidget(parent)
- {
- QHBoxLayout* lay = new QHBoxLayout(this);
- edit = new QTextEdit;
- lay->addWidget(edit);
- edit->setReadOnly(true);
- connect(edit,&QTextEdit::cursorPositionChanged,
- this,&LogBox::highlightCurrentLine);
- }
- LogBox::~LogBox()
- {
- }
- void LogBox::append(const QString& str)
- {
- edit->append(str);
- }
- void LogBox::highlightCurrentLine()
- {
- QList<QTextEdit::ExtraSelection> extraSelections;
- QTextCursor cur = edit->textCursor();
- cur.movePosition(QTextCursor::StartOfBlock);
- cur.clearSelection();
- int curBlock = cur.blockNumber();
- for (bool succ=true;
- cur.blockNumber()==curBlock && succ;
- succ=cur.movePosition(QTextCursor::Down))
- {
- QTextEdit::ExtraSelection selection;
- selection.format.setBackground(QColor(Qt::blue));
- selection.format.setForeground(QColor(Qt::white));
- selection.format.setProperty(QTextFormat::FullWidthSelection, true);
- selection.cursor = cur;
- //selection.cursor.clearSelection();
- extraSelections.append(selection);
- }
- edit->setExtraSelections(extraSelections);
- }
复制代码
|
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
|