Qt is a powerful and versatile C++ framework for developing cross-platform applications with a graphical user interface. When developing graphical applications, it's often important to provide users with the ability to interactively select and display images. This tutorial shows how to display an image after choosing it from the dialog in Qt 6.
The code sets up a simple graphical application using the Qt framework, allowing users to choose and display images. It creates a window with a vertical layout containing a button and a label. Clicking the button opens a file dialog, allowing users to choose an image file. Upon selection, the code retrieves the file path and updates the label to display the chosen image.
#include <QApplication>
#include <QVBoxLayout>
#include <QLabel>
#include <QPushButton>
#include <QFileDialog>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
auto *window = new QWidget();
QVBoxLayout layout(window);
layout.setAlignment(Qt::AlignTop);
QPushButton button("Choose Image", window);
QLabel label(window);
QObject::connect(&button, &QPushButton::clicked, [&]() {
QString filePath = QFileDialog::getOpenFileName(window, "Choose Image", "", "*.png *.jpg *.jpeg");
if (!filePath.isEmpty()) {
label.setPixmap(QPixmap(filePath).scaledToWidth(640));
}
});
layout.addWidget(&button);
layout.addWidget(&label);
window->setLayout(&layout);
window->show();
return QApplication::exec();
}
Leave a Comment
Cancel reply