hamza
hamza

Reputation: 2824

Adding a label to a widget

I am trying to add a label to the main window using Qt. Here is a piece of the code:

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);
    QWidget Main_Window;
    QPixmap Image;

    Image.load("1837.jpg");

    QLabel i_label;
    i_label.setPixmap(Image);
    i_label.show();

    QPushButton Bu_Quit("Quit", &Main_Window);

    QObject::connect(&Bu_Quit, SIGNAL(clicked()), qApp, SLOT(quit()));

    Main_Window.show();
    return app.exec();
}

I've been having a very hard time figuring out how to properly add QLabels to QWidgets, I tried to set the Main_Window as the main widget using this method: app.setMainWidget(Main_Window) and the label was still outside the window. So how do I put labels into widgets using Qt?

Upvotes: 3

Views: 33204

Answers (3)

ando
ando

Reputation: 1

You can try:

QWidget window;

QImage image("yourImage.png");
QImage newImage = image.scaled(150, 150, Qt::KeepAspectRatio);
QLabel label("label", &window);
label.setGeometry(100, 100, 100, 100);
label.setPixmap(QPixmap::fromImage(newImage));

window.show();

this way you can even decide where to put the label and choose the image size.

Upvotes: 0

Barbaris
Barbaris

Reputation: 1266

hamza, this code worked fine for me:

#include <QtGui>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QWidget Main_Window;

    QLabel i_label("Start", &Main_Window);
    //i_label.setPixmap(QPixmap("1837.jpg"));

    QPushButton Bu_Quit("Quit" , &Main_Window);
    QObject::connect(&Bu_Quit , SIGNAL(clicked()), qApp , SLOT(quit()));

    QVBoxLayout *vbl = new QVBoxLayout(&Main_Window);
    vbl->addWidget(&i_label);
    vbl->addWidget(&Bu_Quit);

    Main_Window.show();

    return app.exec();
}

I commented setting the image code to show you that the label was set correctly. Make sure your image is valid (otherwise you won't see the text). The trick here was that you need to use qt layouts like QVBoxLayout

Upvotes: 9

snoofkin
snoofkin

Reputation: 8895

Add the label to a layout widget and set the window layout to that layout.

Design note: its better to create your own MainWindow class, inheriting from QMainWindow for instance, and design it from the inside.

or even better, use QtCreator.

Upvotes: 2

Related Questions