I am new to Qt, and I am trying to create a simple GUI Application that displays an image once a button has been clicked on.
I can read the image in a QImage
object, but is there any simple way to call a Qt function that takes the QImage
as an input, and displays it?
As far as I know, QPixmap
is used for displaying images and QImage
for reading them. There are QPixmap::convertFromImage()
and QPixmap::fromImage()
functions to convert from QImage
.
One common way is to add the image to a QLabel
widget using QLabel::setPixmap()
, and then display the QLabel
as you would any other widget. Example:
#include <QtGui>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QPixmap pm("your-image.jpg");
QLabel lbl;
lbl.setPixmap(pm);
lbl.show();
return app.exec();
}
Simple, but complete example showing how to display QImage might look like this:
#include <QtGui/QApplication>
#include <QLabel>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QImage myImage;
myImage.load("test.png");
QLabel myLabel;
myLabel.setPixmap(QPixmap::fromImage(myImage));
myLabel.show();
return a.exec();
}
Drawing an image using a QLabel
seems like a bit of a kludge to me. With newer versions of Qt you can use a QGraphicsView
widget. In Qt Creator, drag a Graphics View
widget onto your UI and name it something (it is named mainImage
in the code below). In mainwindow.h
, add something like the following as private
variables to your MainWindow
class:
QGraphicsScene *scene;
QPixmap image;
Then just edit mainwindow.cpp
and make the constructor something like this:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this);
image.load("myimage.png");
scene = new QGraphicsScene(this);
scene->addPixmap(image);
scene->setSceneRect(image.rect());
ui->mainImage->setScene(scene);
}
Source: Stackoverflow.com