Get QTextEdit changes when textChanged() signal is emited

℡╲_俬逩灬. 提交于 2021-02-04 18:28:47

问题


I have a QTextEdit and I connected the textChanged() slot to a signal. How can I find the changes when the signal is emitted. For example, I want to save the cursor position and the character written when I write something.


回答1:


In the slot that gets called when the signal is emitted you can get the text with QString str = textEdit->toplainText();. Also you can store the previous version of the string and compare to get the character that was added and its position.

Regarding the cursor position you can us QTextCurosr class as in this example:

widget.h file:

#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

widget.cpp file:

#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()));
}

main.cpp file:

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

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

    return a.exec();
}


来源:https://stackoverflow.com/questions/14553979/get-qtextedit-changes-when-textchanged-signal-is-emited

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!