סטנלי גרונן
סטנלי גרונן

Reputation: 2997

Qt C++11 lambda: Is this connect (signal-slot) correct?

I am using Qt5 (C++11 enabled) on Windows7.
In my app I have something like this:

connect(ui->alarm, &QCheckBox::stateChanged, [this]{
  (ui->alarm->isChecked()) ? m_timer.start() : m_timer.stop();
});

where alarm is QCheckBox and m_timer is a QTimer.

I want to start/stop the timer on-the-fly, according to the status of the alarm check-box.

I tested, It seems to work, but I'm not sure if it's 100% ok... or if there's a better lambda to do it?

Upvotes: 4

Views: 1181

Answers (1)

user3302274
user3302274

Reputation: 292

connect(ui->alarm, &QCheckBox::stateChanged, [this](int state){
  state ? m_timer.start() : m_timer.stop();
});

That way you don't need to refer to ui->alarm.

In QCheckBox::stateChanged(int state), the state really is a

enum Qt::CheckState

Qt::Unchecked = 0 The item is unchecked.

Qt::PartiallyChecked = 1 The item is partially checked. Items in hierarchical models may be partially checked if some, but not all, of their children are checked.

Qt::Checked = 2 The item is checked.

Upvotes: 5

Related Questions