代码之家  ›  专栏  ›  技术社区  ›  Igor

如何通知maxlength溢出

  •  1
  • Igor  · 技术社区  · 6 年前

    在执行默认处理程序之前,有没有连接信号的方法?我正在寻找一种方法,在QLineEdit::textChanged signal之前执行我的函数,以执行关于最大长度限制的通知。

    1 回复  |  直到 5 年前
        1
  •  2
  •   eyllanesc Yonghwan Shin    6 年前

    您可以使用keyPressEvent方法发出自定义信号。

    #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"