Important: Please read the Qt Code of Conduct -

How to access Ui::MainWindow member from sender object?

  • I'm working on an application that has several QPushButtons which perform very similar actions, so I'm trying to capture all of the on_click actions with one slot that fits all.
    In my window constructor I have

    ui(new Ui::MainWindow){

    and then I connected all my buttons to the on_button_clicked() slot, like this:

    connect(ui->btn01, SIGNAL(clicked()), this, SLOT(on_button_clicked()));
    connect(ui->btn02, SIGNAL(clicked()), this, SLOT(on_button_clicked()));

    The on_button_clicked() slot is successfully capturing which button was pressed and then, based on that I get a file name from a QHash where I have all the button object names as keys. I'm trying to use that file name as the background image I want to set to the button:

    //get the button that was pressed
        QPushButton* pressed_btn=qobject_cast<QPushButton*>(sender());
        QString btn_name=pressed_btn->objectName();
        //get the image associated to that button in the map
        QString img=images[btn_name];
        //set a background using the image associated to the pressed button
        ui->pressed_btn->setStyleSheet("#"+btn_name+"{ background-image: url(://"+img+") }");

    However, I get an error saying that pressed_btn is not a member of ui, which is true. The members are btn01, btn02, btn03, etc. so I need to get the proper name that is associated to pressed_btn. I've also tried using ui->btn_name but of course I get the same error, as I need the name inside that variable, not the actual variable identifier (btn_name).
    Is there a way to dereference the actual object from the sender object I'm getting, so I can use it as a member of the ui object?

  • Lifetime Qt Champion

    Hi @anarelle, welcome!

    I think you have multiple options here:

    1. pressed_btn is a pointer, so pressed_btn->setStyleSheet("#"+btn_name+"{ background-image: url(://"+img+") }"); should at least compile, probably also work
    2. There is QSignalMapper, which allows to put an additional parameter to your slot
    3. With the new functor-style connects you can use lambdas or std::bind to pass additional parameters to the slot


  • Thanks! Simply using pressed_btn->setStyleSheet did the trick (compiled and also worked)!

Log in to reply