(QT study notes): encapsulation of custom controls

Encapsulation of custom controls

  • Combination of controls used

Right-click the project to add a new file

  • New ui file added

  • In smallWidget.ui

  • In widget.ui

  • Select the widget, right-click, and upgrade to (select global inclusion to facilitate the next upgrade)

  • The widget control class in the figure becomes the smallWidget type:

  • Then compile and run:

  • Define the external interface in samllWidget.h
//设置值
void setData(int val);
//获取值
int getData();
  • Define the function in samllWidget.cpp
SmallWidget::SmallWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::SmallWidget)
{
    ui->setupUi(this);

    //修改SpinBox  右侧滚动条 跟着移动
    void(QSpinBox:: *spinBoxP)(int) = &QSpinBox::valueChanged;
    connect(ui->spinBox,spinBoxP , [=](int val){
            ui->horizontalSlider->setValue(val);
    });

    //右侧滚动条移动,左侧跟着改变数字
    connect(ui->horizontalSlider,&QSlider::valueChanged , [=](int val){
            ui->spinBox->setValue(val);
    });
}

//设置值
void SmallWidget::setData(int val)
{
    ui->horizontalSlider->setValue(val);

}
//获取值
int SmallWidget::getData()
{
    return ui->horizontalSlider->value();

}
  • Use in widget.cpp
//点击设置按钮,将小控件设置到一半位置
connect(ui->btn_set,&QPushButton::clicked,[=](){
        ui->widget->setData(50);
});

//点击获取按钮,获取当前显示数字
connect(ui->btn_get,&QPushButton::clicked,[=](){
    qDebug() << ui->widget->getData();
});

Guess you like

Origin blog.csdn.net/baidu_41388533/article/details/111564633