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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With