Qt Learning 9 - Encapsulation of custom controls _spinBox and horizontalSlider

The custom control is as shown in the figure below: Pull the horizontalSlider on the right and the spinBox on the left to change the maximum value to 100. Change the value in the spinBox, and the horizontalSlider will also change accordingly. Click to get the current value, and the program will print out the value in the spinBox. Click Set Halfway through, the spinBox changes to 50, and the corresponding horizontalSlider also changes to the middle position
insert image description here

Create a new designer interface.
insert image description here
First, lay out the ui
, which is the layout of horizontalSlider and spinBox.
insert image description here
insert image description here
This is a simple layout of the window interface. A widget is selected. Then the ui in the smallwidget will be placed in this. How to put
insert image description here
the smallwidget in the widget?
insert image description here
Right-click Upgrade to
insert image description here
Just put smallwidget in it, and then add it
Write a global function in smallwidget for subsequent calls
insert image description here
Then add linkage effects in smallwidget.cpp

#include "smallwidget.h"
#include "ui_smallwidget.h"

SmallWidget::SmallWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::SmallWidget)
{
    ui->setupUi(this);
    //QspinBox数字改变 QSlider也跟着滑动
    void(QSpinBox:: * spSignal)(int)=&QSpinBox::valueChanged;
    connect(ui->spinBox,spSignal,ui->horizontalSlider,&QSlider::setValue);
    //QSlider滑动 QspinBox数字随之改变
    connect(ui->horizontalSlider,&QSlider::valueChanged,ui->spinBox,&QSpinBox::setValue);
}
void SmallWidget:: setNum(int num)
{
    ui->spinBox->setValue(num);
}
int SmallWidget:: getNum()
{
    return ui->spinBox->value();
}

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

Add the control program of the button in the widget

#include "widget.h"
#include "ui_widget.h"
#include "QPushButton"
#include "QDebug"
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    connect(ui->btn_get,&QPushButton::clicked,[=](){
        qDebug()<<ui->widget->getNum();
    });
    connect(ui->btn_set,&QPushButton::clicked,[=](){
        ui->widget->setNum(50);
    });
}

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


OK, that's it!

Guess you like

Origin blog.csdn.net/qq_45156021/article/details/109184380