c++ - 在 qt 中的 if 中对不同的进度条使用连接和断开连接

标签 c++ qt

我仍在学习如何使用 Qt(事实上,这是我第一天这样做),但在信号方面遇到了障碍。我想要一个 slider ,其值由进度条复制,直到所述进度条的值达到 50。一旦达到,另一个进度条将“接管”并继续复制 slider 的值。

这是我的代码:

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow){
    ui->setupUi(this);

    ui->progressBar->setValue(ui->horizontalSlider->value());
    ui->progressBar_2->setValue(ui->horizontalSlider->value());

    //connecting the slider with the second progress bar
    connect(ui->horizontalSlider, SIGNAL(valueChanged(int)), ui->progressBar_2, SLOT(setValue(int)));


    if(ui->progressBar_2->value() == 50){ //once the progress bar 2 reach 50
        //disconnects the connection it had with the slider
        disconnect(ui->horizontalSlider, SIGNAL(valueChanged(int)), ui->progressBar_2, SLOT(setValue(int))); 
        //The first progress bar takes on the slider's value (50)
        ui->progressBar->setValue(ui->horizontalSlider->value()); //could also have ui->progressBar->setValue(50) 
        //connect the slider with the first progress bar
        connect(ui->horizontalSlider, SIGNAL(valueChanged(int)), ui->progressBar, SLOT(setValue(int))); 
    }

}

MainWindow::~MainWindow(){
        delete ui;
}

我不知道为什么 if 条件被忽略了。是我写条件的方式还是我不理解 connect() 和 disconnect() 函数?

最佳答案

if 条件在水平 slider 值发生变化的构造函数之外没有任何意义。这里最简单的方法是连接到一个插槽,您可以在其中过滤值并更改 slider 值。例如,创建一个名为 updateSliders(int) 的插槽,然后将其连接到:

connect(ui->horizontalSlider, SIGNAL(valueChanged(int)),
        this, SLOT(updateSliders(int)));

下面是插槽的合适实现:

void MainWindow::updateSliders(int value)
{
  if (value > 50) {
    ui->progressBar_2->setValue(value);
  } else {
    ui->progressBar->setValue(value);
  }
}

关于c++ - 在 qt 中的 if 中对不同的进度条使用连接和断开连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38144071/

相关文章:

c++ - 如何改进 vector 搜索功能?

c++ - 在控制台中打印时如何将循环打印的形状移到文本上

qt - QML 图像 : SSL handshake failed

c++ - Qt中会自动断开连接吗?

c++ - unordered_map 无法检索在参数中指定为变量的键的值

c++ - 如何保持在堆栈上分配的对象的动态类型?

c++ - 警告 : treating 'c-header' input as 'c++-header' when in C++ mode, 此行为已弃用

javascript - QWebFrame addToJavaScriptWindowObject() 对象在 Javascript 中未定义

c++ - 如果 QObject 与信号和插槽一起使用,则替换异常

c++ - Qt 在布局中自动排列小部件