简体   繁体   中英

Qt checking the state of multiple buttons

I am using a StackedLayout and Buttons to switch between screens. I have a separate style for if a button is checked or not. I am also using keyPressEvent to switch between stacks instead of clicking on a button to switch.

When I use the keyPress event, I can switch between stacks, but the buttons don't change from unchecked to checked.

I have 4 buttons and for each I wrote methods to see if the button is checked or not, like so:

bool MainWindow::dashBoardButton_isChecked() {
    if(ui->dashBoardButton->isChecked()) {
        return true;
    } else {
        return false;
    };

    return false;
};

and when I switch between stacks, I use this method:

void MainWindow::on_dashBoardButton_clicked() {
    ui->mainStack->setCurrentIndex(0);

    if(!dashBoardButton_isChecked()) {
        ui->dashBoardButton->setChecked(true);
    };

};

I do this 4 times for each button/stack. This seems to me to be a little repetitive. Is there some way I could shorten the code, and maybe instead of having 4 very similar methods, have one method that instead?

you might use QButtonsGroup or write your own wrapper over group of buttons, so you initialize this wrapper with them providing mapping between button and some value describing which of them is checked, you can connect each button to slot of this wrapper to update value and you might signal this change from a wrapper using signal-slot mechanism. You might use QSignalMapper .

Keypad::Keypad(QWidget *parent)
        : QWidget(parent)
    {
        QSignalMapper *signalMapper = new QSignalMapper(this);
        connect(signalMapper,SIGNAL(mapped(int)),this,SIGNAL(digitClicked(int)));

        for (int i = 0; i < 10; ++i) {
            QString text = QString::number(i);
            buttons[i] = new QPushButton(text, this);
            signalMapper->setMapping(buttons[i], i);
            connect(buttons[i], SIGNAL(clicked()), signalMapper, SLOT(map()));
        }

        createLayout();
    }

http://qt-project.org/doc/qt-5.0/qtcore/qsignalmapper.html

http://doc.qt.digia.com/qq/qq10-signalmapper.html

In mainwindow.h add this:

#include <QPushButton>

and add this prototype:

bool isChecked(QPushButton *btn);

in mainwindow.c add this function:

bool MainWindow::isChecked(QPushButton *btn) {
    if (btn->isChecked())
        return true;
    return false;
}

Now you can use this function to check if your buttons are checked.

ps I've use QPushButton as example.. you have to use the type of your buttons

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM