16

I have to connect focus event from some QLineEdit element (ui->lineEdit) to the method focus(). How can I do this?

jww
  • 97,681
  • 90
  • 411
  • 885
Max Frai
  • 61,946
  • 78
  • 197
  • 306

2 Answers2

29

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).

jww
  • 97,681
  • 90
  • 411
  • 885
Lohrun
  • 6,432
  • 1
  • 24
  • 22
  • 2
    Using this example straight without any change could/will generate the error "constructors not allowed a return type". The solution is to add a ";" after the class definition in MyLineEdit.h – Gustavo Rodríguez Oct 12 '18 at 11:10
  • Also if you got a "no such signal" is because you should not include the qualified name in void focussed(bool hasFocus), it must be void focussed(bool); – Gustavo Rodríguez Oct 12 '18 at 13:19
  • It's still not work i add the ; and focussed(bool), but there is still the message No such signal MyLineEdit::focussed() – sniffi Jul 12 '19 at 05:25
3

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

Christophe Weis
  • 2,518
  • 4
  • 28
  • 32