Check if a widget with focus is a Button or a Slider?

  • Hi I have developed a Simple Gui using Buttons(Push Buttons & Tool Buttons) and Sliders (Dial and slider). The focus keeps on moving from one widget to another during execution. Is there a way to check that the widget which currently has the focus is a button or slider? I was thinking that all the buttons are derived from QAbstractButton and sliders from QAbstractSlider so there should be a function to check which class the current widget belongs to?
    Thanks for any kind of help I am new around Qt and would appreciate any kind of help being provided!

  • Hi
    You can check in "if" statement in your function:
    bool itIsButton = false;
    bool itIsSlider = false;

    return itIsButton = true;
    else if(ui->slider->hasFocus())
    return ItIsSlider = true;
    and then you check the state of itIsButton and itIsSlider.
    You can also do other operation in the "if" statements instead of returning the values.

  • @Slawomir_Piernikowski yes you are correct. but there are multiple button i.e. PushButton, PushButton2 and slo multiple sliders so I have to write if statement for each of the widget seprately. I was hoping for a much simpler solution that would involve less if statement such as one if for all kind of buttons and another if for all kind of sliders. Do you think that's possible?

  • Qt Champions 2017

    Following should help you.

    1. QApplication::focusWidget - It will give you focus widget reference.
    2. Obj->metaObject()->className() will give you class name.
    3. You can utilise the objectName as well.

  • Qt Champions 2018

    @dheerendra said in Check if a widget with focus is a Button or a Slider?:

    Obj->metaObject()->className() will give you class name.

    or just use qobject_cast<> to check if it is from the expected type.

  • Qt Champions 2017

    @abdul_samad how did the issue go?. Are you able to solve this issue ? If the issue is resolved make the issue to SOLVED state so that it helps others.

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.