发出 textChanged() 信号时获取 QTextEdit 更改

Joh*_*ith 5 c++ qt notepad qtextedit

我有一个QTextEdit,我将textChanged()插槽连接到一个信号。发出信号时如何找到变化。比如我想保存光标位置和写东西时写的字符。

Jac*_*ieg 3

在发出信号时调用的插槽中,您可以获得带有 的文本QString str = textEdit->toplainText();。您还可以存储字符串的先前版本并进行比较以获取添加的字符及其位置。

关于光标位置,您可以使用 QTextCurosr 类,如下例所示:

widget.h 文件:

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QTextEdit>
#include <QTextCursor>
#include <QVBoxLayout>
#include <QLabel>

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = 0);

    ~Widget();

private slots:
    void onTextChanged();
    void onCursorPositionChanged();

private:
    QTextCursor m_cursor;
    QVBoxLayout m_layout;
    QTextEdit m_textEdit;
    QLabel m_label;
};

#endif // WIDGET_H
Run Code Online (Sandbox Code Playgroud)

小部件.cpp 文件:

#include "widget.h"

#include <QString>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    connect(&m_textEdit, SIGNAL(textChanged()), this, SLOT(onTextChanged()));
    connect(&m_textEdit, SIGNAL(cursorPositionChanged()), this, SLOT(onCursorPositionChanged()));


    m_layout.addWidget(&m_textEdit);
    m_layout.addWidget(&m_label);

    setLayout(&m_layout);
}

Widget::~Widget()
{

}

void Widget::onTextChanged()
{
    // Code that executes on text change here
}

void Widget::onCursorPositionChanged()
{
    // Code that executes on cursor change here
    m_cursor = m_textEdit.textCursor();
    m_label.setText(QString("Position: %1").arg(m_cursor.positionInBlock()));
}
Run Code Online (Sandbox Code Playgroud)

主.cpp文件:

#include <QtGui/QApplication>
#include "widget.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();

    return a.exec();
}
Run Code Online (Sandbox Code Playgroud)