Creating a Simple Widget by using spinbox and slider in Qt Creator

Experimenting with Qt Creator

Creating a Simple Widget by using spinbox and slider in Qt Creator

Introduction

This is an example of a simple widget using spinbox and slider in a grid layout arranged row-wise. Spinbox and slider are connected through signal and slot mechanism.

Steps for implementation

Follow these steps:

Step 1 : Create widgets of class spinbox and slider.

Step 2 : Set Ranges for spinbox and slider widgets.

Step 3 : Use signal and slot concept ; connect (Object1 , Signal1 ,Object2 , Signal2) to connect spinbox widget with the slider widget.

Step 4 : Now, it's time to put these widgets in the layout. I've selected grid layout in this case and on setting column=0 in the declaration of gridlayout gives QVBoxLayout.

Codes

QWidget_ .pro

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

CONFIG += c++11

# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += \
    main.cpp \
    qwidget_.cpp

HEADERS += \
    qwidget_.h

FORMS +=

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

qwidget_.h

#ifndef QWIDGET__H
#define QWIDGET__H

#include <QMainWindow>

QT_BEGIN_NAMESPACE
QT_END_NAMESPACE

class QWidget_ : public QMainWindow
{
    Q_OBJECT

public:
    QWidget_(QWidget *parent = nullptr);
    ~QWidget_();

private:

};
#endif // QWIDGET__H

main.cpp

#include "qwidget_.h"

#include <QApplication>
#include <QHBoxLayout>
#include <QSlider>
#include<QSpinBox>
#include<QGridLayout>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QWidget *window =new QWidget;
    window -> setWindowTitle("Enter your age");

    QSpinBox *spinBox = new QSpinBox;
    QSlider *slider = new QSlider (Qt::Horizontal);
    spinBox -> setRange(0,200);
    slider -> setRange(0,200);

    QObject :: connect (spinBox, SIGNAL(valueChanged(int)),slider, SLOT(setValue(int)));
    QObject :: connect (slider, SIGNAL(valueChanged(int)),spinBox, SLOT(setValue(int)));

    spinBox -> setValue(100);

    QGridLayout  *glayout= new QGridLayout();
    glayout -> addWidget(spinBox,1,0);
    glayout -> addWidget(slider,2,0);
    window -> setLayout(glayout);

    window->show();
    return app.exec();
}

qwidget_.cpp


#include "qwidget_.h"
#include "ui_qwidget_.h"

QWidget_::QWidget_(QWidget *parent)
    : QMainWindow(parent)

{
}

QWidget_::~QWidget_()
{

}

Output

Enter_age.PNG

Did you find this article valuable?

Support Swati Sarangi by becoming a sponsor. Any amount is appreciated!