Search code examples
qtqwidgetqtguiqmenuqaction

Is there a way to show tooltip on disabled QWidget


I have a Qt form, where I have a button and menu. For various reasons I can disable certain elements, e.g button or some actions in the menu.

Is there a way I could show a tooltip or when the mouse is hovered over the disabled button or menu item with an explanation as to why it is disabled?

I am using Qt 4.8.

Thanks!


Solution

  • You can set the tooltip dynamically based on the state of the QWidget or by simply toggling both at the same time. Upon disabling/enabling the widget from somewhere just call QWidget::setToolTip(...) with the QString you want the tooltip to display when hovering with the mouse over the given widget. For example if you have a public slot called toggleButton(bool toggleFlag) which toggles the enable-setting of a button you can do:

    void MyWidget::toggleButton(bool toggleFlag) {
        this->ui->myButton->setEnabled(toggleFlag);
        this->ui->myButton->setToolTip(toggleFlag ? QString("Enabled wohoo!") : QString("Disabled because I like it"));
    }
    

    You can of course do also change the tooltip by calling QWidget::isEnabled() and act upon its return value. Since you haven't given any code I can only assume how you toggle your button(s) so that's all I can give you for now.


    UPDATE: It was pointed in the comments that tooltips don't work with disabled widgets due not receiving mouse events. Both statements are not true (note that I have used the same tooltip message since due to lack of minimal working example I didn't want to write a whole new project from scratch and used an existing one of mine instead):

    • Hovering a disabled button triggers the tooltip

    enter image description here

    • Hovering an enabled button triggers the tooltip

    enter image description here