我必须将焦点事件从某些QLineEdit元素( ui->lineEdit )连接到方法 focus() 。我怎样才能做到这一点?

最佳答案

当QLineEdit获得焦点时,没有信号发射。因此,将方法连接到焦点事件的想法并不直接合适。

如果想要focused信号,则必须派生QLineEdit类。这是如何实现此目的的示例。

myLineEdit.h文件中,您具有:

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);
};

myLineEdit.cpp文件中,您具有:
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));
}

现在,您可以将MyLineEdit::focussed()信号连接到focus()方法(插槽)。

08-17 05:43