IscanderChe
9 августа 2023 г. 15:39

Пример использования QScintilla C++

К сожалению, из памяти напрочь истёрлось, как я получил дистрибутив (дело было три года назад, и потом я к этой теме не возвращался). Здесь придётся основательно прошерстить интернет. Можно попробовать вот этот ресурс: https://github.com/brCreate/QScintilla Поэтому просто приведу код с некоторыми пояснениями в комментариях.

В итоге должно получиться вот такое приложение.

приложение.про

  1. CONFIG += qscintilla2
  2.  
  3. TARGET = MyQScintillaApplication
  4.  
  5. HEADERS = mainwindow.h
  6. SOURCES = main.cpp mainwindow.cpp
  7. RESOURCES = application.qrc

приложение.qrc

  1. <!DOCTYPE RCC><RCC version="1.0">
  2. <qresource>
  3. <file>images/copy.png</file>
  4. <file>images/cut.png</file>
  5. <file>images/new.png</file>
  6. <file>images/open.png</file>
  7. <file>images/paste.png</file>
  8. <file>images/save.png</file>
  9. </qresource>
  10. </RCC>

main.cpp

  1. #include <QApplication>
  2.  
  3. #include "mainwindow.h"
  4.  
  5. int main(int argc, char *argv[])
  6. {
  7. Q_INIT_RESOURCE(application);
  8.  
  9. QApplication app(argc, argv);
  10. MainWindow mainWin;
  11. mainWin.show();
  12. return app.exec();
  13. }

главное окно.h

  1. #ifndef MAINWINDOW_H
  2. #define MAINWINDOW_H
  3.  
  4. #include <QMainWindow>
  5.  
  6. class QAction;
  7. class QMenu;
  8. class QsciScintilla;
  9.  
  10. class MainWindow : public QMainWindow
  11. {
  12. Q_OBJECT
  13.  
  14. public:
  15. MainWindow();
  16.  
  17. protected:
  18. void closeEvent(QCloseEvent *event);
  19.  
  20. private slots:
  21. void newFile();
  22. void open();
  23. bool save();
  24. bool saveAs();
  25. void about();
  26. void documentWasModified();
  27.  
  28. private:
  29. void createActions();
  30. void createMenus();
  31. void createToolBars();
  32. void createStatusBar();
  33. void readSettings();
  34. void writeSettings();
  35. bool maybeSave();
  36. void loadFile(const QString &fileName);
  37. bool saveFile(const QString &fileName);
  38. void setCurrentFile(const QString &fileName);
  39. QString strippedName(const QString &fullFileName);
  40.  
  41. QsciScintilla *textEdit;
  42. QString curFile;
  43.  
  44. QMenu *fileMenu;
  45. QMenu *editMenu;
  46. QMenu *helpMenu;
  47. QToolBar *fileToolBar;
  48. QToolBar *editToolBar;
  49. QAction *newAct;
  50. QAction *openAct;
  51. QAction *saveAct;
  52. QAction *saveAsAct;
  53. QAction *exitAct;
  54. QAction *cutAct;
  55. QAction *copyAct;
  56. QAction *pasteAct;
  57. QAction *aboutAct;
  58. QAction *aboutQtAct;
  59. };
  60.  
  61. #endif

главное окно.cpp

  1. #include <QAction>
  2. #include <QApplication>
  3. #include <QCloseEvent>
  4. #include <QFile>
  5. #include <QFileInfo>
  6. #include <QFileDialog>
  7. #include <QIcon>
  8. #include <QMenu>
  9. #include <QMenuBar>
  10. #include <QMessageBox>
  11. #include <QPoint>
  12. #include <QSettings>
  13. #include <QSize>
  14. #include <QStatusBar>
  15. #include <QTextStream>
  16. #include <QToolBar>
  17.  
  18. #include <Qsci/qsciscintilla.h>
  19. #include <Qsci/qscistyle.h>
  20. #include <Qsci/qscilexercpp.h>
  21.  
  22. #include "mainwindow.h"
  23.  
  24. MainWindow::MainWindow()
  25. {
  26. textEdit = new QsciScintilla;
  27. setCentralWidget(textEdit);
  28.  
  29. createActions();
  30. createMenus();
  31. createToolBars();
  32. createStatusBar();
  33.  
  34. readSettings();
  35.  
  36. connect(textEdit, SIGNAL(textChanged()), this, SLOT(documentWasModified()));
  37.  
  38. setCurrentFile("");
  39.  
  40. textEdit->append("Append text");
  41. textEdit->setUtf8(true);
  42.  
  43. //! Текущая строка кода и ее подсветка
  44. textEdit->setCaretLineVisible(true);
  45. textEdit->setCaretLineBackgroundColor(QColor("yellow"));
  46.  
  47. //! Выравнивание
  48. textEdit->setAutoIndent(true);
  49. textEdit->setIndentationGuides(false);
  50. textEdit->setIndentationsUseTabs(true);
  51. textEdit->setIndentationWidth(4);
  52.  
  53. //! margin это полоска слева, на которой обычно располагаются breakpoints
  54. textEdit->setMarginsBackgroundColor(QColor("gainsboro"));
  55. textEdit->setMarginLineNumbers(1, true);
  56. textEdit->setMarginWidth(1, 50);
  57.  
  58. //! Авто-дополнение кода в зависимости от источника
  59. textEdit->setAutoCompletionSource(QsciScintilla::AcsAll);
  60. textEdit->setAutoCompletionCaseSensitivity(true);
  61. textEdit->setAutoCompletionReplaceWord(true);
  62. textEdit->setAutoCompletionUseSingle(QsciScintilla::AcusAlways);
  63. textEdit->setAutoCompletionThreshold(0);
  64.  
  65. //! Подсветка соответствий скобок
  66. textEdit->setBraceMatching(QsciScintilla::SloppyBraceMatch);
  67. textEdit->setMatchedBraceBackgroundColor(Qt::yellow);
  68. textEdit->setUnmatchedBraceForegroundColor(Qt::blue);
  69.  
  70. //! Линия ограничения кода
  71. textEdit->setEdgeColor(Qt::green);
  72. textEdit->setEdgeColumn(80);
  73. textEdit->setEdgeMode(QsciScintilla::EdgeMode::EdgeLine);
  74.  
  75. //! Установки текстового редактора
  76. textEdit->setColor(Qt::green);
  77. textEdit->setFont(QFont("Verdana"));
  78. textEdit->setPaper(Qt::black);
  79. textEdit->setWhitespaceForegroundColor(Qt::white);
  80. textEdit->setWhitespaceVisibility(QsciScintilla::WhitespaceVisibility::WsVisible);
  81. }
  82.  
  83. void MainWindow::closeEvent(QCloseEvent *event)
  84. {
  85. if (maybeSave()) {
  86. writeSettings();
  87. event->accept();
  88. } else {
  89. event->ignore();
  90. }
  91. }
  92.  
  93. void MainWindow::newFile()
  94. {
  95. if (maybeSave()) {
  96. textEdit->clear();
  97. setCurrentFile("");
  98. }
  99. }
  100.  
  101. void MainWindow::open()
  102. {
  103. if (maybeSave()) {
  104. QString fileName = QFileDialog::getOpenFileName(this);
  105. if (!fileName.isEmpty())
  106. loadFile(fileName);
  107. }
  108. }
  109.  
  110. bool MainWindow::save()
  111. {
  112. if (curFile.isEmpty()) {
  113. return saveAs();
  114. } else {
  115. return saveFile(curFile);
  116. }
  117. }
  118.  
  119. bool MainWindow::saveAs()
  120. {
  121. QString fileName = QFileDialog::getSaveFileName(this);
  122. if (fileName.isEmpty())
  123. return false;
  124.  
  125. return saveFile(fileName);
  126. }
  127.  
  128. void MainWindow::about()
  129. {
  130. QMessageBox::about(this, tr("About Application"),
  131. tr("The <b>Application</b> example demonstrates how to "
  132. "write modern GUI applications using Qt, with a menu bar, "
  133. "toolbars, and a status bar."));
  134. }
  135.  
  136. void MainWindow::documentWasModified()
  137. {
  138. setWindowModified(textEdit->isModified());
  139. }
  140.  
  141. void MainWindow::createActions()
  142. {
  143. newAct = new QAction(QIcon(":/images/new.png"), tr("&New"), this);
  144. newAct->setShortcut(tr("Ctrl+N"));
  145. newAct->setStatusTip(tr("Create a new file"));
  146. connect(newAct, SIGNAL(triggered()), this, SLOT(newFile()));
  147.  
  148. openAct = new QAction(QIcon(":/images/open.png"), tr("&Open..."), this);
  149. openAct->setShortcut(tr("Ctrl+O"));
  150. openAct->setStatusTip(tr("Open an existing file"));
  151. connect(openAct, SIGNAL(triggered()), this, SLOT(open()));
  152.  
  153. saveAct = new QAction(QIcon(":/images/save.png"), tr("&Save"), this);
  154. saveAct->setShortcut(tr("Ctrl+S"));
  155. saveAct->setStatusTip(tr("Save the document to disk"));
  156. connect(saveAct, SIGNAL(triggered()), this, SLOT(save()));
  157.  
  158. saveAsAct = new QAction(tr("Save &As..."), this);
  159. saveAsAct->setStatusTip(tr("Save the document under a new name"));
  160. connect(saveAsAct, SIGNAL(triggered()), this, SLOT(saveAs()));
  161.  
  162. exitAct = new QAction(tr("E&xit"), this);
  163. exitAct->setShortcut(tr("Ctrl+Q"));
  164. exitAct->setStatusTip(tr("Exit the application"));
  165. connect(exitAct, SIGNAL(triggered()), this, SLOT(close()));
  166.  
  167. cutAct = new QAction(QIcon(":/images/cut.png"), tr("Cu&t"), this);
  168. cutAct->setShortcut(tr("Ctrl+X"));
  169. cutAct->setStatusTip(tr("Cut the current selection's contents to the "
  170. "clipboard"));
  171. connect(cutAct, SIGNAL(triggered()), textEdit, SLOT(cut()));
  172.  
  173. copyAct = new QAction(QIcon(":/images/copy.png"), tr("&Copy"), this);
  174. copyAct->setShortcut(tr("Ctrl+C"));
  175. copyAct->setStatusTip(tr("Copy the current selection's contents to the "
  176. "clipboard"));
  177. connect(copyAct, SIGNAL(triggered()), textEdit, SLOT(copy()));
  178.  
  179. pasteAct = new QAction(QIcon(":/images/paste.png"), tr("&Paste"), this);
  180. pasteAct->setShortcut(tr("Ctrl+V"));
  181. pasteAct->setStatusTip(tr("Paste the clipboard's contents into the current "
  182. "selection"));
  183. connect(pasteAct, SIGNAL(triggered()), textEdit, SLOT(paste()));
  184.  
  185. aboutAct = new QAction(tr("&About"), this);
  186. aboutAct->setStatusTip(tr("Show the application's About box"));
  187. connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
  188.  
  189. aboutQtAct = new QAction(tr("About &Qt"), this);
  190. aboutQtAct->setStatusTip(tr("Show the Qt library's About box"));
  191. connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
  192.  
  193. cutAct->setEnabled(false);
  194. copyAct->setEnabled(false);
  195. connect(textEdit, SIGNAL(copyAvailable(bool)), cutAct, SLOT(setEnabled(bool)));
  196. connect(textEdit, SIGNAL(copyAvailable(bool)), copyAct, SLOT(setEnabled(bool)));
  197. }
  198.  
  199. void MainWindow::createMenus()
  200. {
  201. fileMenu = menuBar()->addMenu(tr("&File"));
  202. fileMenu->addAction(newAct);
  203. fileMenu->addAction(openAct);
  204. fileMenu->addAction(saveAct);
  205. fileMenu->addAction(saveAsAct);
  206. fileMenu->addSeparator();
  207. fileMenu->addAction(exitAct);
  208.  
  209. editMenu = menuBar()->addMenu(tr("&Edit"));
  210. editMenu->addAction(cutAct);
  211. editMenu->addAction(copyAct);
  212. editMenu->addAction(pasteAct);
  213.  
  214. menuBar()->addSeparator();
  215.  
  216. helpMenu = menuBar()->addMenu(tr("&Help"));
  217. helpMenu->addAction(aboutAct);
  218. helpMenu->addAction(aboutQtAct);
  219. }
  220.  
  221. void MainWindow::createToolBars()
  222. {
  223. fileToolBar = addToolBar(tr("File"));
  224. fileToolBar->addAction(newAct);
  225. fileToolBar->addAction(openAct);
  226. fileToolBar->addAction(saveAct);
  227.  
  228. editToolBar = addToolBar(tr("Edit"));
  229. editToolBar->addAction(cutAct);
  230. editToolBar->addAction(copyAct);
  231. editToolBar->addAction(pasteAct);
  232. }
  233.  
  234. void MainWindow::createStatusBar()
  235. {
  236. statusBar()->showMessage(tr("Ready"));
  237. }
  238.  
  239. void MainWindow::readSettings()
  240. {
  241. QSettings settings("Trolltech", "Application Example");
  242. QPoint pos = settings.value("pos", QPoint(200, 200)).toPoint();
  243. QSize size = settings.value("size", QSize(400, 400)).toSize();
  244. resize(size);
  245. move(pos);
  246. }
  247.  
  248. void MainWindow::writeSettings()
  249. {
  250. QSettings settings("Trolltech", "Application Example");
  251. settings.setValue("pos", pos());
  252. settings.setValue("size", size());
  253. }
  254.  
  255. bool MainWindow::maybeSave()
  256. {
  257. if (textEdit->isModified()) {
  258. int ret = QMessageBox::warning(this, tr("Application"),
  259. tr("The document has been modified.\n"
  260. "Do you want to save your changes?"),
  261. QMessageBox::Yes | QMessageBox::Default,
  262. QMessageBox::No,
  263. QMessageBox::Cancel | QMessageBox::Escape);
  264. if (ret == QMessageBox::Yes)
  265. return save();
  266. else if (ret == QMessageBox::Cancel)
  267. return false;
  268. }
  269. return true;
  270. }
  271.  
  272. void MainWindow::loadFile(const QString &fileName)
  273. {
  274. QFile file(fileName);
  275. if (!file.open(QFile::ReadOnly)) {
  276. QMessageBox::warning(this, tr("Application"),
  277. tr("Cannot read file %1:\n%2.")
  278. .arg(fileName)
  279. .arg(file.errorString()));
  280. return;
  281. }
  282.  
  283. QTextStream in(&file);
  284. QApplication::setOverrideCursor(Qt::WaitCursor);
  285. textEdit->setText(in.readAll());
  286. QApplication::restoreOverrideCursor();
  287.  
  288. setCurrentFile(fileName);
  289. statusBar()->showMessage(tr("File loaded"), 2000);
  290. }
  291.  
  292. bool MainWindow::saveFile(const QString &fileName)
  293. {
  294. QFile file(fileName);
  295. if (!file.open(QFile::WriteOnly)) {
  296. QMessageBox::warning(this, tr("Application"),
  297. tr("Cannot write file %1:\n%2.")
  298. .arg(fileName)
  299. .arg(file.errorString()));
  300. return false;
  301. }
  302.  
  303. QTextStream out(&file);
  304. QApplication::setOverrideCursor(Qt::WaitCursor);
  305. out << textEdit->text();
  306. QApplication::restoreOverrideCursor();
  307.  
  308. setCurrentFile(fileName);
  309. statusBar()->showMessage(tr("File saved"), 2000);
  310. return true;
  311. }
  312.  
  313. void MainWindow::setCurrentFile(const QString &fileName)
  314. {
  315. curFile = fileName;
  316. textEdit->setModified(false);
  317. setWindowModified(false);
  318.  
  319. QString shownName;
  320. if (curFile.isEmpty())
  321. shownName = "untitled.txt";
  322. else
  323. shownName = strippedName(curFile);
  324.  
  325. setWindowTitle(tr("%1[*] - %2").arg(shownName).arg(tr("Application")));
  326. }
  327.  
  328. QString MainWindow::strippedName(const QString &fullFileName)
  329. {
  330. return QFileInfo(fullFileName).fileName();
  331. }

По статье задано0вопрос(ов)

1

Вам это нравится? Поделитесь в социальных сетях!

IscanderChe
  • 13 сентября 2023 г. 19:11

По горячим следам (с другого форума вопрос задали, пришлось в памяти освежить всё) решил дополнить.

  1. Качаем исходники с https://riverbankcomputing.com/software/qscintilla/download .
  2. Распаковываем в любой удобный каталог.
  3. С помощью Qt Creator собираем релиз библиотеки.
  4. Пробуем собрать пример из поставки.
  5. Далее читаем прилагающуюся к исходникам html-документацию.

Комментарии

Только авторизованные пользователи могут публиковать комментарии.
Пожалуйста, авторизуйтесь или зарегистрируйтесь