在qt

时间:2016-07-01 11:17:39

标签: c++ qt

我还在学习如何使用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()函数?

1 个答案:

答案 0 :(得分:2)

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);
  }
}