1

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:

zhm
  • 3,513
  • 3
  • 34
  • 55
David
  • 25
  • 3

1 Answers1

3

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] == ' ')
zhm
  • 3,513
  • 3
  • 34
  • 55
  • Wow it works, thank you very much, I was actually blocked for hours on this one, you just save me thanks – David Mar 30 '17 at 06:00
  • Glad to help. You can `accept` my answer if it solves your problem. :-) – zhm Mar 30 '17 at 06:03