Notanik z kolorowaniem składni Qt

0

Witam. Próbuje się nauczyć używania syntax, znalazłem przykład na stronie qt i przepisałem go do swojego projektu. Problem polega na tym że gdy go uruchamiam program zawiesza się gdy tylko próbuje wpisać słowo kolorowane.

#ifndef HIGHLIGHTER_H
#define HIGHLIGHTER_H

#include <QSyntaxHighlighter>

class Highlighter : public QSyntaxHighlighter
{
    Q_OBJECT
public:
    explicit Highlighter(QTextDocument *parent = 0);
protected:
    void highlightBlock(const QString &text);
private:
    struct HighlightingRule
    {
        QTextCharFormat format;
        QRegExp pattern;
    };

    QVector<HighlightingRule> rules;

    QRegExp commentStarExpression;
    QRegExp commentEndExpression;

    QTextCharFormat keywords;
    QTextCharFormat classes;
    QTextCharFormat singleLineComments;
    QTextCharFormat multiLineComments;
    QTextCharFormat quotes;
    QTextCharFormat functions;
};

#endif // HIGHLIGHTER_H
 
 #include "highlighter.h"

Highlighter::Highlighter(QTextDocument *parent) :
    QSyntaxHighlighter(parent)
{
    HighlightingRule rule;

    // keywords rules
    keywords.setForeground(Qt::darkBlue);
    keywords.setFontWeight(QFont::Bold);
    QStringList keywordPatterns;
    keywordPatterns << "\\bchar\\b" << "\\bclass\\b" << "\\bconst\\b"
                       << "\\bdouble\\b" << "\\benum\\b" << "\\bexplicit\\b"
                       << "\\bfriend\\b" << "\\binline\\b" << "\\bint\\b"
                       << "\\blong\\b" << "\\bnamespace\\b" << "\\boperator\\b"
                       << "\\bprivate\\b" << "\\bprotected\\b" << "\\bpublic\\b"
                       << "\\bshort\\b" << "\\bsignals\\b" << "\\bsigned\\b"
                       << "\\bslots\\b" << "\\bstatic\\b" << "\\bstruct\\b"
                       << "\\btemplate\\b" << "\\btypedef\\b" << "\\btypename\\b"
                       << "\\bunion\\b" << "\\bunsigned\\b" << "\\bvirtual\\b"
                       << "\\bvoid\\b" << "\\bvolatile\\b";
    foreach(const QString &pattern, keywordPatterns)
    {
        rule.format = keywords;
        rule.pattern = QRegExp(pattern);
        rules.append(rule);
    }

    // qt classes rule
    classes.setForeground(Qt::magenta);
    classes.setFontWeight(QFont::Bold);
    rule.pattern = QRegExp("\\bQA-Za-z\\b");
    rule.format = classes;
    rules.append(rule);

    // quotes rule
    quotes.setForeground(Qt::darkGreen);
    rule.pattern = QRegExp("\".*\"");
    rule.format = quotes;
    rules.append(rule);

    // functions rule
    functions.setForeground(Qt::darkYellow);
    rule.pattern = QRegExp("\\b[A-Za-z0-9_]+(?=\\()");
    rule.format = functions;
    rules.append(rule);

    // single line comment rule
    singleLineComments.setForeground(Qt::red);
    rule.pattern = QRegExp("//[^\n]*");
    rule.format = singleLineComments;
    rules.append(rule);

    //multi line comments
    commentStarExpression = QRegExp("/\\*");
    commentEndExpression = QRegExp("\\*/");
}
void Highlighter::highlightBlock(const QString &text)
{
    foreach (const HighlightingRule &rule, rules) {
        QRegExp expression(rule.pattern);
        int index = expression.indexIn(text);
        while(index>=0)
        {
            int length = expression.matchedLength();
            setFormat(index, length, rule.format);
            index = expression.indexIn(text, index - length);
        }
    }
    setCurrentBlockState(0);

    int startIndex = 0;
    if(previousBlockState() != 1)
        startIndex = commentStarExpression.indexIn(text);
    while(startIndex >= 0)
    {
          int endIndex = commentEndExpression.indexIn(text, startIndex);
          int commentLength;
          if(endIndex != -1){
                setCurrentBlockState(1);
                commentLength = text.length() - startIndex;
          } else {
                commentLength = endIndex - startIndex + commentEndExpression.matchedLength();
          }
          setFormat(startIndex, commentLength, multiLineComments);
          startIndex = commentStarExpression.indexIn(text, startIndex + commentLength );
    }
}
 #ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include "highlighter.h"
#include <QTextEdit>
namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT
    
public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    
private slots:
    void on_actionOpen_triggered();

    void on_actionSave_triggered();

    void on_actionExit_triggered();

private:
    Ui::MainWindow *ui;
    QTextEdit *editor;
    Highlighter *highlighter;
};

#endif // MAINWINDOW_H
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "highlighter.h"
#include <QString>
#include <QFile>
#include <QMessageBox>
#include <QTextStream>
#include <QFileDialog>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    editor = ui -> textEdit;
    highlighter = new Highlighter(editor->document());
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_actionOpen_triggered()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"),
                                                    QString(), tr("Text Files (*.txt);;C++ Files (*.cpp *.h)"));

    if(!fileName.isEmpty())
    {
        QFile file(fileName);
        if(!file.open(QIODevice::ReadOnly))
        {
            QMessageBox::critical(this, tr("Error"), tr("Could not open file"));
            return;
        }
        QTextStream in(&file);
        ui -> textEdit -> setText(in.readAll());
        file.close();
    }
}
void MainWindow::on_actionSave_triggered()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"),
                                                    QString(), tr("Text Files (*.txt);;C++ Files (*.cpp *.h)"));

    if(!fileName.isEmpty())
    {
        QFile file(fileName);
        if(!file.open(QIODevice::WriteOnly))
        {
            QMessageBox::critical(this, tr("Error"), tr("Could not save file"));
            return;
        }
        QTextStream out(&file);
        out << ui -> textEdit -> toPlainText();
        file.close();
    }
}

void MainWindow::on_actionExit_triggered()
{
    if(editor->document()->isModified())
    {
       QMessageBox::StandardButton reply =  QMessageBox::question(this, tr("Unsaved changes"), tr("This document has unsaved changes.\n Do you want to save?"),
                              QMessageBox::Yes | QMessageBox::No);
       if(reply == QMessageBox::Yes)
       {
           on_actionSave_triggered();
           qApp -> quit();
       }
    }
    qApp -> quit();
}
 

I jescze jedno. Programy w qt creator kompilują się jedyni w trybie release, w debug nie chcą, ktoś wie dlaczego?

0

Jeżeli coś Ci się nie kompiluje, to podaj komunikat jaki się przy tym wyświetla, wątpię by komukolwiek chciało się przeglądać podany przez Ciebie kod w poszukiwaniu nieznanego problemu, a taki komunikat z pewnością oszczędziłby sporo szukania.

0

Jak program się zawiesi to daj pause na debuggerze i przejrzyj call stack - na której pętli program wisi.

0

To podczas kompilowania w trybie debug.

Error while building/deploying project TextEditor (kit: Desktop Qt 5.0.2 MSVC2012 64bit)
Podczas wykonywania kroku "Make"

A w trybie release kompiluje się, ale zawiesza gdy wpisuje coś co powinno być podświetlone.
--Edit--
A mógłbyś mi dokładnie powiedzieć o co chodzi? Bo wyświetla mi zdecydowanie zbyt dużą ilość ilość assemblera jak na moje umiejętności.

0

Qt creator

0

Już po problemie.
Zamiast

index = expression.indexIn(text, index + length);

miałem

index = expression.indexIn(text, index - length);

Zarejestruj się i dołącz do największej społeczności programistów w Polsce.

Otrzymaj wsparcie, dziel się wiedzą i rozwijaj swoje umiejętności z najlepszymi.