Adding a label to a widget

前端 未结 3 1999
醉酒成梦
醉酒成梦 2021-01-21 05:49

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);
    QWi         


        
相关标签:
3条回答
  • 2021-01-21 05:57

    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

    0 讨论(0)
  • 2021-01-21 06:04

    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 讨论(0)
  • 2021-01-21 06:23

    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.

    0 讨论(0)
提交回复
热议问题