how to notify that the maxlength is overflowing

只谈情不闲聊 提交于 2019-12-11 07:53:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!