问题描述
我试图使用Qt添加一个标签到主窗口。下面是一段代码:
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();
}
我一直很努力地想办法如何正确添加 QLabel
到 QWidget
,我试图设置 Main_Window
作为主要的小部件使用这个方法: app.setMainWidget(Main_Window)
,标签仍然在窗口外面。那么如何使用Qt将标签放入小部件?
I've been having a very hard time figuring out how to properly add QLabel
s to QWidget
s, 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,这个代码对我很好:
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();
}
我评论了设置图像代码以显示标签设置正确。确保您的图片有效(否则您将看不到文字)。这里的诀窍是,您需要使用qt布局,如
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
这篇关于将标签添加到窗口小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!