Important: Please read the Qt Code of Conduct -

Enable the clear button action in a read-only QLineEdit?

  • Hi,

    Perhaps I'm doing this the wrong way, but I have a QLineEdit control that's displaying the name of a file chosen using a file browser. At the moment it's not read-only, but I'm having issues with it being that way when the control has focus then focus moves elsewhere. One solution is to make it read-only, and only be able to set the contents programmatically (i.e. from the file browser results or by a "clear" button). Now, obviously, QLineEdit has its own clear button, which works well until I set the QLineEdit as read only, which appears to disable the clear button!

    Is there a way to retain the clear button functionality while keeping the control read-only?

    Hope that makes sense!

    Many thanks

  • I've found a way of doing this, but don't know if it's 'a good idea'. Once my ui is setup, I execute this loop:

    for (int i(0); i < ui->lineEdit->children().size(); ++i)
        QAction *clearAction(qobject_cast<QAction *>(ui->lineEdit->children().at(i)));
        if (clearAction)

    I'm fairly new to Qt, as you might have guessed, so can anyone tell me if this makes sense and/or if there is a better way?


  • Lifetime Qt Champion

    Hi and welcome to the forums
    i was not aware read only would disable button also. :)
    Well, there is nothing bad about finding it and enable it again as such.
    Only thing is that if another action was added in later version, code
    might not do as expected. But slim chance that will happen.
    The loop is fine, but you could just do

    QAction* clearAction = ui->lineEdit->findChild<QAction*>();
     if (clearAction)

  • @mrjj Thanks for that suggestion; it's a bit cleaner! You're right though, it's the possibility of other actions being added that make this solution seem a bit unreliable in the long run. It would be nice to be able to search for the action based on the name given to it, but that's:

        static const char clearButtonActionNameC[] = "_q_qlineeditclearaction";

    in qlineedit.cpp (see I believe.

    The other thing may have been to check the icon of the action found matches that set in qlineedit.cpp at:

        QAction *clearAction = new QAction(d->clearButtonIcon(), QString(), this);

    But the clearButtonIcon() is in (QLineEditPrivate) which, I believe is bad form to try to use.


Log in to reply