Display QImage within main window
-
23-06-2021 - |
سؤال
I'm trying to display an image with Qt, I can get it to appear in a separate window, but I can't make it appear within the main window
Qt_first w;
w.show();
This shows the window I designed in Qt designer, how do I access the Qlabel(Image_Lbel) I put within the QWidget (centralWidget) of that window?
I generated a stripy image that shows correctly, just not within the correct window
QSize size = QSize(640,480);
QImage::Format format = QImage::Format_ARGB32;
QImage image = QImage::QImage(size, format);
//generate
QLabel myLabel;
myLabel.setPixmap(QPixmap::fromImage(image));
myLabel.show();
I get the feeling it could be I haven't included the files from the creator or the namespaces any suggestion much appreciated
المحلول
I guess your Label
is getting displayed independently. Set the parent of label to your main window. Then your Label
will displayed inside your main window.
So use,
QLabel *myLabel = new QLabel(this); // sets parent of label to main window
myLabel->setPixmap(QPixmap::fromImage(image));
myLabel->show();
You can also use move function for moving your label within the main window.
نصائح أخرى
If you want to set the label from outside the Qt_first
class, you need to add a method to do this. For example (in qt_first.cpp, change qt_first.h accordingly):
void Qt_first::setImageLabel(const QImage& image)
{
ui->Image_Lble.setPixmap(QPixmap::fromImage(image));
}
ui
in this example is the object that represents the UI that you created with Qt Designer.
I used a combination of both answers, thanks to both
Qt_first w; // the UI I made with Qt creator
QLabel *myLabel = w.getImageLabel();
myLabel->setPixmap(QPixmap::fromImage(image));
w.show();
With the following inside the Qt_first class
QLabel* Qt_first::getImageLabel(){
QLabel *myLabel = ui.Image_Label;
return myLabel;
}