首页 > 解决方案 > 为什么 Qt SIGNAL(clicked(bool) 与真正的鼠标点击行为不同?

问题描述

我在我的小部件中添加了一个 QPushButton 并将其设置为可检查。并在其插槽功能中添加一些代码,如下所示。如果我用鼠标单击此按钮 1,一切正常。但是,如果我通过以下方式将其与信号连接:

connect(ui->button2,SIGNAL(clicked(bool)),this,SLOT(on_button1_clicked(bool)));

并用鼠标单击 button2,执行 on_button1_clicked(bool checked),但是 button1 背景颜色不会改变。

有没有人提出一些建议?

void MainWindow::on_button1_clicked(bool checked)
{
    if(checked)
    {       
       //some work here.....
        ui->button1->setText(tr("on "));
       //.......
    }
    else
    {
       //some work here.......
        ui->button1->setText(tr("off "));
       //......
    }
}

标签: c++qtqt5

解决方案


您应该改为连接button2tobutton1setChecked(bool)插槽。

我只是看了看的来源,QAbstractButton::setChecked(bool)它确实发出了一个信号,虽然不是clicked(bool),但是toggled(bool)

因此,将您的重命名on_button1_clicked(bool)on_button1_toggled并将您的连接更改为:

connect(ui->button2, SIGNAL(clicked(bool)), ui->button1, SLOT(setChecked(bool))); 

推荐阅读