c++ - 尝试删除 QTextEdit 中的单词时出现 Qt 简单错误

标签 c++ qt qwidget qtextedit qtextstream

我想在 QTextEdit 上按空格后删除一个词。

这是我的代码:

窗口.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

窗口.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();
        }
    }
}

主要.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();
}

所以对于这段代码,当我写“abc”时,它应该删除所有单词,但它却返回一个错误:

最佳答案

在你的write()中,如果word.length()等于0,word[word.length()-1]引用了无效的word[-1]

您应该在 if 语句中检查 word.length() >= 1:

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

关于c++ - 尝试删除 QTextEdit 中的单词时出现 Qt 简单错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43109107/

相关文章:

c++ - freopen 在我的应用程序关闭之前不会写入数据

c++ - 插槽未被使用

python - 具有状态栏和菜单栏的 PyQt QWidget

c++ - 从子部件中删除 QGraphicsEffect

c++ - 用于测试目的 : which floating point (IEEE754 32b) numbers are "special"?

c++ - Win7应用程序崩溃后如何调试?

c++ - 使用 Media Foundation source reader 读取 3D(左右)视频

c++ - 替换表的列值(如果存在)

c++ - c++11 编译器中出现额外限定错误的问题

c++ - 将 QString 转换为 Local8bit,然后将 String 转换为 QString