1

I build a new element which is inherited from QWidget and is a combination of a LineEdit and a Button.

enter image description here

Now when I click into the button, a list should be shown (or in another word, a completer should be shown).

enter image description here

Now the requirement is, when I click the mouse outside the completer, the completer will be closed. So I need to know the global coordinate of the mouse to check if the mouse is inside the completer or not. How can I do it?

LineEditWithButton.h

class LineEditWithButton : public QWidget
{
  Q_OBJECT
public:
  LineEditWithButton( QWidget *p_parent = nullptr );      
  void showCompleter(); /* This function shows the Completer */
  .............

protected:
  void keyPressEvent( QKeyEvent *p_event ) override;
  void mousePressEvent( QMouseEvent *p_event ) override;
  .........

private slots:      
  void toggleCompleter(); /* slot to hide/show the completer */      
  void lineEditChanged(); /* slot when text in the LineEdit changes */
  .............

private:      
  MyButton *m_button = nullptr; /* This variable holds the Button beside the LineEdit */      
  MyLineEdit *m_lineEdit = nullptr; /* This variable holds the LineEdit */      
  MyCompleter *m_completer = nullptr; /* This variable holds the Completer */
  .........
};

LineEditWithButton.cpp

void LineEditWithButton::mousePressEvent( QMouseEvent *p_event )
{
  QPoint globalPosition = p_event->globalPos();
  QRect compRect = m_completer->geometry();
  if ( !compRect.contains( globalPosition ) && m_completer->isVisible() )
  {
     m_completer->hide();
  }
}

This function does not work for me. I set a breakpoint in this function but the breakpoint is not be hit. How can I solve my problem ?

songvan
  • 369
  • 5
  • 21
  • 1
    What if you set your completer's window flag to be `Qt::Popup`? That will make it act like a popup menu. – vahancho Nov 02 '18 at 13:52
  • @vahancho: thanks for your idea. I checked it. It works, but when the completer is shown, the focus is in the completer, meanwhile I need the focus always on the LineEditWithButton. ( I think it should be like that, because if the focus is in the completer, then we can not write anything in the LineEdit any more. I think the idea of the completer is we can always write in the LineEdit, and the suggestion will be updated in the completer while we write in the LineEdit. – songvan Nov 02 '18 at 14:30

0 Answers0