How to connect focus event from QLineEdit?

后端 未结 2 1622
隐瞒了意图╮
隐瞒了意图╮ 2020-12-29 09:25

I have to connect focus event from some QLineEdit element (ui->lineEdit) to the method focus(). H

相关标签:
2条回答
  • 2020-12-29 10:07

    There is no signal emitted when a QLineEdit gets the focus. So the notion of connecting a method to the focus event is not directly appropriate.

    If you want to have a focused signal, you will have to derive the QLineEdit class. Here is a sample of how this can be achieved.

    In the myLineEdit.h file you have:

    class MyLineEdit : public QLineEdit
    {
      Q_OBJECT
    
    public:
      MyLineEdit(QWidget *parent = 0);
      ~MyLineEdit();
    
    signals:
      void focussed(bool hasFocus);
    
    protected:
      virtual void focusInEvent(QFocusEvent *e);
      virtual void focusOutEvent(QFocusEvent *e);
    };
    

    In the myLineEdit.cpp file you have :

    MyLineEdit::MyLineEdit(QWidget *parent)
     : QLineEdit(parent)
    {}
    
    MyLineEdit::~MyLineEdit()
    {}
    
    void MyLineEdit::focusInEvent(QFocusEvent *e)
    {
      QLineEdit::focusInEvent(e);
      emit(focussed(true));
    }
    
    void MyLineEdit::focusOutEvent(QFocusEvent *e)
    {
      QLineEdit::focusOutEvent(e);
      emit(focussed(false));
    }
    

    You can now connect the MyLineEdit::focussed() signal to your focus() method (slot).

    0 讨论(0)
  • 2020-12-29 10:09

    I assume you mean connect as in signals/slots, focus event isn't a signal it's a virtual method you have to override in order to change the behavior:

    http://doc.qt.io/qt-5/qlineedit.html#focusInEvent

    0 讨论(0)
提交回复
热议问题