3

我添加QSliderQSpinBox使用此代码

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

我想添加其中的 30 个,如何循环添加?

4

2 回答 2

4

我会通过以下方式做到这一点:

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);
于 2013-10-28T21:55:52.933 回答
0

您应该看看Qt 信号映射器,因为这正是它的设计目的。

信号映射器类对信号进行分组,然后根据输入整数、QString 或小部件参数重新发送它们。

我将把信号映射作为练习留给读者。

于 2013-10-28T21:02:19.800 回答