【问题标题】:Why a Qt SIGNAL(clicked(bool) does not same with a really mouse clicked behavior?为什么 Qt SIGNAL(clicked(bool) 与真正的鼠标点击行为不同?
【发布时间】:2019-09-07 10:07:41
【问题描述】:

我在我的小部件中添加了一个 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 "));
       //......
    }
}

【问题讨论】:

  • 你打电话给ui->button2->setCheckable(true);了吗?
  • 是的。我愿意。我调用 ui->button2->setCheckable(true);在构造函数中。
  • “背景颜色不变”是什么意思?你想让 button1 看起来像是被按下了吗?
  • 是的。它是。 qt Designer 将 button1 和 button2 都设置为可检查。当我按下它时,它的背景颜色会自动改变。

标签: c++ qt qt5


【解决方案1】:

您应该将您的button2 连接到button1setChecked(bool) 插槽。

我刚刚看了the source of 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))); 

【讨论】:

  • 非常感谢 Martin Hennings 先生。有效。在我根据您的建议修改代码之后。你太棒了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-08
  • 1970-01-01
  • 1970-01-01
  • 2019-08-19
  • 1970-01-01
  • 2018-03-15
  • 2011-06-22
相关资源
最近更新 更多