QT add Label to certain position

Hongxu Jin picture Hongxu Jin · Sep 6, 2016 · Viewed 12.5k times · Source

I'm new to QT and I want to know how to add a label on a certain position by code. I create a new application and I have these code automatically:

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

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

I want to add a label to a certain position, for example, its geometry is (10, 10, 30, 80). How do I do this by code? Someone can help me?

Answer

Arnav Borborah picture Arnav Borborah · Sep 6, 2016

You need to create an instance of QLabel, like this: (Here is the example from the docs. Try implementing it yourself with your standards. The docs are helpful)

QLabel *label = new QLabel(this);
label->setFrameStyle(QFrame::Panel | QFrame::Sunken);
label->setText("first line\nsecond line");
label->setAlignment(Qt::AlignBottom | Qt::AlignRight);
//Here is how to change position:
label->setGeometry(QRectF(10,10,30,80));

By the way, here is what an example QLabel looks like:

Text Label