Important: Please read the Qt Code of Conduct -

How to bind a event handler to qtCheckbox

  • Hi all,
    I'm newbie with Qt.
    Now, I'm writing a program generate a list of checkbox. With each checkbox, I want to bind it with a checked event.
    Is there a way to do this? How to create a event delegate and bind a handler to a checkbox in the fly?


  • Moderators

    Sorry, I do not understand what you want to do.

  • Sorry for my english.
    In fact, I want to create a list of checkbox dynamically, in the fly.
    I want that when I click any checkbox, only one function is called.
    So, is it clear? I don't know how to connect the function executing and the checkbox created.

  • Moderators

    So where is the problem? You create some checkboxes and connect their checked() signal to some slot... nothing tricky there.

    You might want to use a QSignalMapper or sender() to find out which checkbox has triggered the signal.

  • What you might do, is use QSignalMapper to create something like this:

    //piece of code that creates the checkboxes
    QSignalMapper* mapper = new QSignalMapper(this);

    for (int i(0); i< 10; ++i) {
    QCheckBox* cb = new QCheckBox(this);
    // put cb in a layout or something like that
    connect(cb, SIGNAL(toggled ( bool checked )), mapper, SLOT(map()));
    mapper->setMapping(cb, i);

    connect(mapper, SIGNAL(mapped(int)), this, SLOT(checkboxClicked(int)));

    // and later on:
    void MyClass::checkboxClicked(int checkboxId)
    //do something

    Of course, you can also choose one of the other mappings if those are more convenient for you. You can map to an int, to a QString, to a QObject* or to a QWidget*.

  • Thanks, I've done it.
    It's better to change "toggled ( bool checked )" to "stateChanged(int)" for checkbox.

    @connect(cb, SIGNAL( stateChanged(int) ), mapper, SLOT(map()));@

    Thank all.

  • Hi, i am new to qt.

    I have create a same function as andre but i cant find a way the get the value of the checkbox that was clicked.

    @QSignalMapper* mapper = new QSignalMapper(this);
    QMultiMap<QString, QString>::iterator a = examination.find("test_id");
    while (a != examination.end() && a.key() == "test_id") {
    QCheckBox* cb = new QCheckBox(a.value(),this);
    connect(cb, SIGNAL( stateChanged(int) ), mapper, SLOT(map()));
    mapper->setMapping(cb, i);

    connect(mapper, SIGNAL(mapped(QString)), this, SLOT(checkboxClicked(QString)));

    void QXSRExample::checkboxClicked(QString checkbox){


    for example if the first checkbox has the value "A" i want to know..
    what can i do?

Log in to reply