C++ 向小部件添加标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5734209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding a label to a widget
提问by hamza
I am trying to add a label to the main window using Qt. Here is a piece of the code:
我正在尝试使用 Qt 向主窗口添加标签。这是一段代码:
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 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?
我一直很难弄清楚如何正确地将QLabel
s添加到QWidget
s,我尝试Main_Window
使用此方法将s设置为主小部件:app.setMainWidget(Main_Window)
并且标签仍在窗口外。那么如何使用 Qt 将标签放入小部件中呢?
回答by Barbaris
hamza, this code worked fine for me:
hamza,这段代码对我来说很好用:
#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
我评论了设置图像代码以向您显示标签设置正确。确保您的图片有效(否则您将看不到文本)。这里的技巧是你需要使用QVBoxLayout这样的 qt 布局
回答by snoofkin
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.
设计说明:最好创建自己的 MainWindow 类,QMainWindow
例如继承自,并从内部设计。
or even better, use QtCreator
.
甚至更好,使用QtCreator
.
回答by ando
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.
通过这种方式,您甚至可以决定放置标签的位置并选择图像大小。