我肯定不是100%我正确理解你的问题。 您可以编写一个继承自QLineEdit
的类,以在其选择发生变化时发出信号。
下面是这样一个类的一个简单例子:它需要原生信号selectionChanged
并且有两个新信号发出有关已更改文本的信息,以显示可能的结果。我还加入了一个简单的对话框来展示如何使用它(即使它只是一种粗糙的方式)。
lineedit.h
#ifndef MYLINEEDIT_H
#define MYLINEEDIT_H
#include <QLineEdit>
class LineEdit: public QLineEdit
{
Q_OBJECT
public:
LineEdit(QWidget *parent = 0): QLineEdit(parent)
{
connect(this, SIGNAL(selectionChanged()), this, SLOT(textSelectionChanged()));
}
public slots:
void textSelectionChanged() {
emit selectionChanged(this->selectedText());
emit selectionChanged(this->selectionStart(), this->selectedText().length());
}
signals:
void selectionChanged(const QString&);
void selectionChanged(int , int);
};
#endif
dialog.h
#ifndef MYDIALOG_H
#define MYDIALOG_H
#include <QDialog>
#include <QtCore>
class Dialog : public QDialog
{
Q_OBJECT
public:
Dialog(QWidget *parent = 0) : QDialog(parent) {}
public slots:
void textChanged(const QString &string) {
qDebug() << string;
}
void textChanged(int start, int length) {
qDebug() << "Start"<< start << ", length: " << length;
}
};
#endif
main.cc(出于完整性)
#include <QApplication>
#include "dialog.h"
#include "lineedit.h"
#include <QHBoxLayout>
int main(int argc, char** argv)
{
QApplication app(argc, argv);
Dialog dialog;
QHBoxLayout *layout = new QHBoxLayout(&dialog);
LineEdit lineedit;
layout->addWidget(&lineedit);
QObject::connect(&lineedit,SIGNAL(selectionChanged(QString)), &dialog, SLOT(textChanged(QString)));
QObject::connect(&lineedit,SIGNAL(selectionChanged(int,int)), &dialog, SLOT(textChanged(int,int)));
dialog.show();
return app.exec();
}
让我知道如果这有帮助。