Search code examples
c++qtqwidgetqtexteditqtextstream

Qt simple error when trying to delete a word in QTextEdit


I'm trying to delete a word after pressing space on a QTextEdit.

Here's my code:

window.h:

#ifndef WINDOW_H
#define WINDOW_H
#include <QApplication>
#include <QWidget>
#include <QTextEdit>
#include <iostream>
using namespace std;

class Window: public QWidget
{
    Q_OBJECT

public:
    Window();

public slots:
    void write();

private:
    QTextEdit *textEdit;
};

#endif // WINDOW_H

window.cpp:

#include "window.h"

Window::Window()
{
    setFixedSize(500, 500);
    textEdit = new QTextEdit(this);
    textEdit->resize(500, 500);
    QObject::connect(textEdit, SIGNAL(textChanged()), this, SLOT(write()));
}

void Window::write()
{
    QString word = textEdit->toPlainText();
    if (word[word.length()-1] == ' ')
    {
        for(int i=0;i<word.length();i++)
        {
            textEdit->textCursor().deletePreviousChar();
        }
    }
}

main.cpp

#include <QApplication>
#include <QTextEdit>
#include <iostream>
#include <QString>
#include "window.h"
using namespace std;

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    Window window;
    window.show();

    return app.exec();
}

So with this code, when I'm writing "abc ", it should erase all the word, but instead it return me an error:


Solution

  • In your write(), if word.length() equals to 0, word[word.length()-1] refers to word[-1], which is invalid.

    You should check if word.length() >= 1 in your if statement:

    if (word.length() >= 1 && word[word.length()-1] == ' ')