如何在QT中制作多个其他小部件的小部件

时间:2017-08-22 08:54:28

标签: qt qt-creator qt-designer

我是Qt的新手,我正在使用qt creator进行GUI设计,现在我必须制作一个动态表单,其中为每个功能添加标签,行编辑和按钮,如长度,宽度等。但是功能不是静态的,有时可能有2个功能,其他时间可能有6个功能,具体取决于xml文件。我想创建一个小部件,每个功能创建一个实例。

我使用以下方法制作了分组小部件的基本结构:

cal_widget.h

#ifndef CAL_WIDGET_H
#define CAL_WIDGET_H

#include <QWidget>
#include<QVBoxLayout>
#include<QPushButton>
#include<QLineEdit>
class cal_widget : public QWidget
{
    Q_OBJECT
public:
    explicit cal_widget(QWidget *parent = nullptr);
    QVBoxLayout* layout;
    QPushButton* btn;
    QLineEdit* ln1;
    QLineEdit* ln2;

signals:

public slots:
};

#endif // CAL_WIDGET_H

cal_widget.cpp

#include "cal_widget.h"

cal_widget::cal_widget(QWidget *parent) : QWidget(parent)
{
    layout = new QVBoxLayout();
    btn= new QPushButton();
    ln1 = new QLineEdit("mm");
    ln2 = new QLineEdit("pix");

    layout->addWidget(ln1);
    layout->addWidget(btn);
    layout->addWidget(ln2);
    this->setLayout(layout);
}

以另一种形式mainwidget.cpp调用上面的小部件

{
QVBoxLayout* vbox = new QVBoxLayout();
cal_widget* cal1 = new cal_widget(this);
cal_widget* cal2 = new cal_widget(this);
cal_widget* cal3 = new cal_widget(this);
cal_widget* cal4 = new cal_widget(this);
cal_widget* cal5 = new cal_widget(this);
vbox->addWidget(cal1);
vbox->addWidget(cal2);
vbox->addWidget(cal3);
vbox->addWidget(cal4);
vbox->addWidget(cal5);
ui->scrollArea->setLayout(vbox);
}

我得到的结果为:this

我怎样才能得到所需result

1 个答案:

答案 0 :(得分:2)

DONE

cal_widget.h

#include "cal_widget.h"

cal_widget::cal_widget(const QString& feature, QWidget *parent) : QGroupBox(parent)
{
    this->setTitle(feature);
    layout = new QGridLayout();
    btn= new QPushButton("OK");
    ln1 = new QLineEdit("mm");
    ln2 = new QLineEdit("pix");

    layout->addWidget(ln1,0,0);
    layout->addWidget(ln2,0,1);
    layout->addWidget(btn,1,0,1,2);
    this->setLayout(layout);
}

cal_widget.cpp

package Library;
use Type::Library -base, -declare => qw(Datetime);
use Type::Utils -all;
use Types::Standard -all;
use DateTime::Format::ISO8601;

class_type Datetime, { class => 'DateTime' };
coerce Datetime,
  from Str, via { DateTime::Format::ISO8601->parse_datetime($_) };

declare 'MyType', as Dict[ name => Str, date => Datetime ], coercion => 1;