1

I tried to add two buttons for my line edit. The "clear" appears only when the text in line edit not empty, and the "bulb" is always shown.

MyLineEdit.cpp

MyLineEdit::MyLineEdit( QWidget *p_parent ) : QLineEdit( p_parent )
{
  m_buttonAction = addAction( QIcon( ":/bulb" ), QLineEdit::TrailingPosition );
  QToolButton *button = dynamic_cast<QToolButton *>( m_buttonAction->associatedWidgets().at( 1 ) );
  button->setCursor( QCursor( Qt::PointingHandCursor ) );
  m_buttonAction->setVisible( true );

  m_clearAction = addAction( QIcon( ":/clear" ), QLineEdit::TrailingPosition );
  QToolButton *clear = dynamic_cast<QToolButton *>( m_clearAction->associatedWidgets().at( 1 ) );
  clear->setCursor( QCursor( Qt::PointingHandCursor ) );
  m_clearAction->setVisible( false );

  connect( this, &MyLineEdit::textChanged, this, &MyLineEdit::toggleClearButton );
  connect( m_clearAction, &QAction::triggered, this, &QLineEdit::clear );
  connect(m_buttonAction, &QAction::triggered, this, &MyLineEdit::doSomething);
}

void MyLineEdit::toggleClearButton()
{
  text().isEmpty() ? m_clearAction->setVisible( false ) : m_clearAction->setVisible( true );
}

void MyLineEdit::doSomething()
{
}

MyLineEdit.h

 class MyLineEdit : public QLineEdit
 {
  Q_OBJECT
  public:
      MyLineEdit( QWidget *p_parent = nullptr );

  private slots:
      void toggleClearButton();
      void doSomething();

  private:
      QAction *m_clearAction = nullptr;
      QAction *m_buttonAction = nullptr;
 };

When I run the program, the "bulb" does not appear at the beginning enter image description here

Only when I type something in the line edit, the "bulb" is then shown as I want enter image description here

Why is the "bulb" not shown at the beginning, where do I have error here?

songvan
  • 369
  • 5
  • 21
  • Your code seems to be working (at least on my system), so double check if the code is actually the same and make sure you have rebuilt the application (so that you don't run an older build). If you still have issues please share the operating system you use and qt version. On win 10 with Qt 5.12 (.4 i think) it works as expected – Zlatomir Jul 29 '19 at 19:50
  • @Zlatomir: thanks, I am using Qt 5.9.6 and Win10. Did the "bulb" appear at the beginning by your side? For me, it still does not work, the "bulb" only appears when I type something. I do not know where I am wrong here? :( – songvan Jul 30 '19 at 12:12
  • Yes, the icon appears at start-up. I don't have Qt 5.9 installed, so i can't check if it's a bug, did you double check your code and if you have a correct build? – Zlatomir Jul 30 '19 at 18:06
  • Also the style doesn't look standard, can you check/share the style sheet, or at least the QLineEdit part? – Zlatomir Jul 30 '19 at 18:12
  • thanks, I have found the error, I have other functions and they affect the result. This constructor does not have error. – songvan Aug 02 '19 at 15:15

0 Answers0