How to hide action button when QLineEdit is disabled?

321 views Asked by At

I have a class which is inherited from QLineEdit, and I set an icon as an action button for this.

MyEdit::MyEdit( QWidget *p_parent ) : QLineEdit( p_parent )
{
  m_buttonAction = addAction( QIcon( "search.png" ), QLineEdit::TrailingPosition );
  QAbstractButton *button = qobject_cast<QAbstractButton *>( m_buttonAction->associatedWidgets().last() );
  m_buttonAction->setVisible( false );
  connect( m_buttonAction, &QAction::triggered, this, &MyEdit::openCompleter );

  m_completer = new QCompleter( this );
  m_sourceModel = new CompleterSourceModel( m_completer );
  m_view = new CompleterView();
  m_view->setStyle( &m_style );
  m_delegate = new CompleterDelegate( m_view );
  m_completer->setPopup( m_view );
  m_completer->setModel( m_sourceModel );
  m_view->setItemDelegate( m_delegate );
  setCompleter( m_completer );
}

void MyEdit::setDataForCompleter( const CompleterData &p_data )
{
  m_sourceModel->setCompleterData( p_data );
  m_buttonAction->setVisible( p_data.data().size() > 0 ); 
}

When I import data for completer, the icon is always shown. Now I need to hide this icon in case MyEdit is disabled or as ReadOnly. I am thinking about override setDisabled and setReadOnly for my class, and in there setVisible for the icon. But these functions are not virtual, so can not be overridden. I am thinking also about a signal like stateChanged of my class, so I can do it in a slot. But I can not find any signal like that for QLineEdit. Do you have any idea how to do it?

1

There are 1 answers

1
trif-ant On

You can handle events QEvent::ReadOnlyChange or QEvent::EnabledChange by overriding the QLineEdit::event method

UPDATE:

Here is an example implementation:

bool MyEdit::event(QEvent *e) override {
    const auto type = e->type();
    if (type == QEvent::ReadOnlyChange || type == QEvent::EnabledChange) {
        m_buttonAction->setVisible(m_sourceModel->rowCount() > 0 ? isEnabled() && isReadOnly() : false);
    }
    return QLineEdit::event(e);
}