我有一个QTextEdit
,我将textChanged()
插槽连接到一个信号。发出信号时如何找到变化。例如,我想保存光标位置和写东西时写的字符。
问问题
15042 次
1 回答
3
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();
}
于 2013-01-28T02:25:11.730 回答