在qt中使用连接和断开不同的进度条

Using connect and disconnect for different progress bars in an if in qt

本文关键字:断开 qt 连接      更新时间:2023-10-16

我还在学习如何使用Qt(事实上这是我第一天这样做),我遇到了一个障碍,当它涉及到信号。我想要一个滑块它的值被进度条复制直到进度条的值达到50。一旦完成,另一个进度条将"接管"并继续复制滑块的值。

下面是我的代码:
#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条件在构造函数之外没有任何意义,您的水平滑动条值正在改变。这里最简单的方法是连接到一个插槽,在那里过滤值并更改滑块值。例如,创建一个名为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);
  }
}