Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/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
    John



  • 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)
        {
            clearAction->setEnabled(true);
            break;
        }
    }
    

    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?

    John


  • Lifetime Qt Champion

    @John-McCabe
    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)
       clearAction->setEnabled(true); 
    


  • @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 https://github.com/Satius/qt5/blob/master/qtbase/src/widgets/widgets/qlineedit.cpp) 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 https://code.woboq.org/qt5/qtbase/src/widgets/widgets/qlineedit_p.h.html (QLineEditPrivate) which, I believe is bad form to try to use.

    John


Log in to reply