问题
Is there a way to connect a signal before executing a default handler? I'm looking for a way to execute my function prior to QLineEdit::textChanged signal to execute notification about maximum length limit.
GTK+ has connect_before(), connect() and connect_after(). Is there something similar in Qt?
回答1:
You can use the keyPressEvent method to issue the custom signal.
#include <QtWidgets>
class LineEdit: public QLineEdit
{
Q_OBJECT
public:
using QLineEdit::QLineEdit;
signals:
void maxLengthSignal();
protected:
void keyPressEvent(QKeyEvent *event) override{
if(!event->text().isEmpty() && maxLength() == text().length())
emit maxLengthSignal();
QLineEdit::keyPressEvent(event);
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
LineEdit w;
QObject::connect(&w, &QLineEdit::textEdited, [](const QString & text){
qDebug()<< text;
});
QObject::connect(&w, &LineEdit::maxLengthSignal, [](){
qDebug()<< "maxLength signal";
});
w.setMaxLength(10);
w.show();
return a.exec();
}
#include "main.moc"
来源:https://stackoverflow.com/questions/53695621/how-to-notify-that-the-maxlength-is-overflowing