我想在 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/