2

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?

songvan
  • 369
  • 5
  • 21
  • 1
    You cannot override the functions, but you can still declare `setDisabled()` for example, and hide the base class implementation – Minh Oct 09 '20 at 11:15
  • @NgocMinhNguyen: thank you very much! I've made it. :) Have a nice day! – songvan Oct 09 '20 at 11:28

1 Answers1

1

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);
}
trif-ant
  • 41
  • 5