侧边栏壁纸
博主头像
三味的小站博主等级

世界上没有偶然,有的只是必然的结果。

  • 累计撰写 61 篇文章
  • 累计创建 13 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录
Qt

QScintilla使用

三味线
2021-12-21 / 0 评论 / 0 点赞 / 14 阅读 / 3637 字

QScintilla是一个支持高亮、自动补全、页边(显示行号、断点)等功能的代码编辑控件

下载:https://riverbankcomputing.com/software/qscintilla/download

需要注意它的不同版本依赖不同的Qt版本,我使用的是Qt5.6.3 + QScintilla-2.11.6

1. 下载完成后,用Qt Creator打开./Qt4Qt5/qscintilla.pro 编译出debug或release库

2. 建立自己的工程,在pro中添加头文件和库依赖

INCLUDEPATH += {YOUR PATH}/QScintilla-2.11.6/Qt4Qt5
win32:CONFIG(release, debug|release): LIBS += -L{YOUR PATH}/QScintilla-2.11.6/build-qscintilla-Qt_5_6_3-Debug/release/ -lqscintilla2_qt5
else:win32:CONFIG(debug, debug|release): LIBS += -L{YOUR PATH}/QScintilla-2.11.6/build-qscintilla-Qt_5_6_3-Debug/debug/ -lqscintilla2_qt5d
else:unix: LIBS += -L{YOUR PATH}/QScintilla-2.11.6/build-qscintilla-Qt_5_6_3-Debug/ -lqscintilla2_qt5

3. 以下为测试代码

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <Qsci/qscilexerjavascript.h>
class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
};
class QsciLexerJSTest : public QsciLexerJavaScript
{
public:
    const char *keywords(int set) const;
};
#endif // MAINWINDOW_H
#include "mainwindow.h"
#include <Qsci/qsciscintilla.h>
#include <Qsci/qsciapis.h>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    QsciScintilla *editor=new QsciScintilla(this);
    // 设置解析器
//    QsciLexerJavaScript *textLexer = new QsciLexerJavaScript;
    QsciLexerJSTest *textLexer = new QsciLexerJSTest;
    editor->setLexer(textLexer);
    // 行号提示
    editor->setMarginType(0, QsciScintilla::NumberMargin);
    editor->setMarginLineNumbers(0, true);
    editor->setMarginWidth(0, 15);
    // 字体
    editor->setFont(QFont("Courier New"));
    // 编码
    editor->SendScintilla(QsciScintilla::SCI_SETCODEPAGE, QsciScintilla::SC_CP_UTF8);
    editor->setAutoIndent(true);
    editor->setCaretLineVisible(false);
    editor->setIndentationGuides(true);
    // 括号
    editor->setUnmatchedBraceBackgroundColor(Qt::blue);
    editor->setBraceMatching(QsciScintilla::SloppyBraceMatch);
    // 自动补全提示
    QsciAPIs *apis = new QsciAPIs(textLexer);
    apis->add(QString("import"));
    apis->add(QString("importPackage"));
    // 也可通过文件设置,一个单词一行
//    if (!apis->load(QString("F:/MyProjects/qscitest/comp_word.txt"))) {
//        qDebug()<<"faild to load";
//    }
    apis->prepare();
    editor->setAutoCompletionSource(QsciScintilla::AcsAll);
    editor->setAutoCompletionCaseSensitivity(true);
    editor->setAutoCompletionThreshold(1);
    textLexer->setColor(QColor(Qt::blue),QsciLexerJavaScript::KeywordSet2);
    this->setCentralWidget(editor);
    this->resize(800, 600);
}
MainWindow::~MainWindow()
{
}
// 自定义关键字,可设置字体、颜色等(QsciLexerJavaScript::KeywordSet2)
const char *QsciLexerJSTest::keywords(int set) const
{
    if(set == 2) {
        return "self moment";
    }
    return QsciLexerJavaScript::keywords(set);
}

0

评论区