我有一个QTextEdit,我将textChanged()插槽连接到一个信号.如何在发出信号时找到更改.例如,我想保存光标位置和写东西时写的字符. 最佳答案 在槽当信号被发射可以得到与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
widget.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()));
}
main.cpp文件:
#include <QtGui/QApplication>
#include "widget.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}