Skip to main content

Command Palette

Search for a command to run...

How to create a form widget in QtCreator for entering personal details

Experimenting with Layouts

Updated
2 min read
How to create a form widget in QtCreator for entering personal details
S

An Electrical Engineer who is enthusiastic about coding , currently working with Qt and taking up these challenges in twitter to build connstructive habits.

#100DaysOfCode

#100DaysOfWriting

#100DaysOfReading

#100DaysOfMeditation

Introduction

This is a program to create a form widget using objects of QLineEdit and QLabel. QLabel objects are used to show text whereas QLineEdit objects are used to take inputs from the users. These objects of QLineEdit and QLabel are arranged in Gridlayout.

Steps for implementation

Following are the steps to achieve this design:

Step 1: Create an object for the main widget (window) and set a title for it.

Step 2: Create an object for the GridLayout .

Step 3: Create objects of QLabel and corresponding QLineEdit. In this example, I've taken 3 entries. So, I've created 3 sets of objects of QLabel and QLineEdits.

Step 4: Now, it's time to add these widgets to the GLayout with the orientation of row and column. Repeat this step for all three sets of objects of QLabel and QLineEdit.

Step 5: Create an object of QPushButton and add it to the GLayout along with its orientation.

Step 6: Addition of all widgets to the GLayout is completed at Step 5 . Now, this GLayout is to be added to the main widget (window). Then, display the main widget.

Codes

#include "mainwindow.h"

#include <QApplication>
#include<QtGui>
#include<QTCore>
#include<QWidget>
#include<QGridLayout>
#include<QLabel>
#include<QLineEdit>
#include<QPushButton>


int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QWidget *window = new QWidget;
    window->setWindowTitle("Personal Details");

    QGridLayout *glayout=new QGridLayout;

    QLabel *label1 = new QLabel("Name :");
    QLineEdit *txt1= new QLineEdit;

    QLabel *label2 = new QLabel("Address :");
    QLineEdit *txt2= new QLineEdit;

    QLabel *label3 = new QLabel("Profession:");
    QLineEdit *txt3= new QLineEdit;


    glayout ->addWidget(label1,0,0);
    glayout ->addWidget(txt1,0,1);

    glayout ->addWidget(label2,1,0);
    glayout ->addWidget(txt2,1,1);

    glayout ->addWidget(label3,2,0);
    glayout ->addWidget(txt3,2,1);

    QPushButton *button = new QPushButton("OK");
    glayout ->addWidget(button,3,0);


    window->setLayout(glayout);
    window->show();
    return a.exec();
}

Output

PersonalDetails-1.PNG

Know Qt

Part 3 of 11

In this series, I will discuss about the pre-requisites to learn Qt. I will also be discussing the confusions cropped up in my mind as a beginner of Qt. I hope it helps you in your journey!

Up next

Example of Nested Layout

Horizontal Layout nested within Vertical Layout