开发者

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?


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜