Question

First let me say, I'm new to QTCreator. I have the UI setup for all of the following just can't figure out how to properly connect the signals and slots:

Ok,so here is my problem. I have 5 SpinBoxes all with a max value of 10 and minimum value of 0, all of which start at 0 . I have a label with the value of 25. When I change the value of the spinbox with the +/- buttons, I want the label to either subtract or add back too the label of 25. In addition, once the value of 25 reaches 0 I want all spinboxes disabled for adding.

(Unfortunately, since I set this all up using the Form creator, all the code is default.

Example:

Label: 1
SB1: 5
SB2: 10
SB3: 2
SB4: 6
SB5: 1

All the values of the SpinBoxes equal 24. When the plus button is hit the value will be 25 for all boxes. Thus I want all the + buttons disabled and when the - button is pressed, I want the enabled.

Was it helpful?

Solution

Here is the code assuming that you have a form class with a label and 5 spinboxes.

Header:

class MainWindow : public QMainWindow {
  Q_OBJECT

public:
  explicit MainWindow(QWidget *parent = 0);
  ~MainWindow();

private:
  Ui::MainWindow *ui;
  double sum;
  QList<QSpinBox*> spinboxes;

private slots:
  void spinbox_value_changed();

};

Source:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
  sum = 25;
  ui->setupUi(this);
  spinboxes << ui->spinBox_1 << ui->spinBox_2 << ui->spinBox_3
            << ui->spinBox_4 << ui->spinBox_5;
  foreach(QSpinBox* spinbox, spinboxes) {
    connect(spinbox, SIGNAL(valueChanged(int)),
            this, SLOT(spinbox_value_changed()));
    spinbox->setRange(0, sum);
  }
  spinbox_value_changed();
}

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

void MainWindow::spinbox_value_changed() {
  double current_sum = 0;
  foreach(QSpinBox* spinbox, spinboxes) {
    current_sum += spinbox->value();
  }
  double points_left = sum - current_sum;
  if (points_left < 0) {
    foreach(QSpinBox* spinbox, spinboxes) {
      spinbox->setValue(0);
    }
    return;
  }
  foreach(QSpinBox* spinbox, spinboxes) {
    if (points_left == 0) {
      spinbox->setMaximum(spinbox->value());
    } else {
      spinbox->setMaximum(sum);
    }
  }
  ui->label->setText(QString().setNum(points_left));
}

I hope the code is self-explanatory. Spinboxes don't make their buttons disabled on my system (though they might when using another style) but the plus buttons stop working when the max sum is reached.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top