Search code examples
c++qttaggingqpushbuttonqt5.3

Tagging Qt Widgets


Is it possible to tag Qt Widgets? I am generating QPushButtons programmatically and as far as I know, there is no way to differentiate them. I checked the documentation and couldn't find anything. What would be an alternative?

    for(int i = 0; i < 6; i++) {
        QPushButton *s = new QPushButton("Select");
        ...
    }

Solution

  • The best way is to set object name to this buttons. For example.

    for(int i = 0; i < 6; i++) {
        QPushButton *s = new QPushButton("Select");
        s->setObjectName("But" + QString::number(i));
    }
    

    Also you can setProperty() to button and read it in future by property() method

    Edit:

    Moreover you can set not unique objectNames. Suppose you want set background color for some buttons. Then you shoudn't apply stylesheet for this buttons yourself. Just set same objectName to this buttons.

    for(int i = 0; i < 6; i++) {
        QPushButton *s = new QPushButton("Select");
        if(i%2 == 0)
             s->setObjectName("red");
    }
    

    And apply next styleSheet

    #red
    {
        background-color: red
    }
    

    And this buttons will be painted in red color.