문제

I add QSlider and QSpinBox with this code

QSpinBox *spinner2 = new QSpinBox;
QSlider *slider2   = new QSlider(Qt::Vertical);
spinner2->setRange(2,100);
slider2->setRange(2,100);
QObject::connect(spinner2, SIGNAL(valueChanged(int)), slider2, SLOT(setValue(int)));
QObject::connect(slider2, SIGNAL(valueChanged(int)), spinner2, SLOT(setValue(int)));
spinner2->setValue(10);

QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(slider2);
layout->addWidget(spinner2);

I would like to add 30 of them, how can I do it by a loop?

도움이 되었습니까?

해결책

I would do that in the following way:

QWidget *widget = new QWidget;

// The main layout of the widget that will hold multiple spinner-slider pairs.
QVBoxLayout *mainLayout = new QVBoxLayout;

for (int i = 0; i < 30; i++) {
    QSpinBox *spinner2 = new QSpinBox(widget);
    QSlider *slider2   = new QSlider(Qt::Vertical, widget);
    spinner2->setRange(2, 100);
    slider2->setRange(2, 100);
    QObject::connect(spinner2, SIGNAL(valueChanged(int)), slider2, SLOT(setValue(int)));
    QObject::connect(slider2, SIGNAL(valueChanged(int)), spinner2, SLOT(setValue(int)));
    spinner2->setValue(10);

    QHBoxLayout *layout = new QHBoxLayout;
    layout->addWidget(slider2);
    layout->addWidget(spinner2);

    mainLayout->addLayout(layout);
}

widget->setLayout(mainLayout);

다른 팁

You should have a look at the Qt signal mapper because that is exactly what it's designed to do.

The signal mapper class groups signals, and then reemits them based on an input integer, QString, or widget parameters.

I'll leave the signal mapping as an exercise to the reader.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top