Qt Demo

Basics of UI creation

For this exercise we will use QT Creator to design a simple image viewer

Make sure you have a qtImage directory in your w01-intro folder.

Run qtcreator then File->Open File or Project select the file ~/cs40/examples/CMakeLists.txt

In QT Creator you can edit, save, compile, and run code. It even integrates with your git repo.

When opening the project for the first time, QT Creator will ask for a build directory. Make a new directory build in your ~/cs40/examples folder and point QT Creator here

Click on the computer icon in the lower left and set the running application to qtimgtest. Click the green arrow to build and run this application. A simple window should pop up.

UI Design

click on mainwindow.ui in qtimage directory in QT Creator. Here you can add widgets and adjust the layout.

In the upper right corner, select the MainWindow widget. You can edit this widgets properties in the lower right menu. Find the windowTitle property and change it to "My First QT App". Run the QT green arrow again and see that the title has changed.

Adding Widgets

Promoting Widgets

Slots and Signals

Graphical user interfaces such as QT have event handling mechanisms to process events like keypresses, mouse clicks, and menu selection. In QT this mechanism uses slots and signals. Events emit signals which can then be sent to slots.

Add functionality to myimagebox.h

#include <QtWidgets>

...

public slots:
    void open();

private:
    QLabel *imageLabel;
    QScrollArea *scrollArea;
    QGridLayout *layout;
Implement in myimagebox.cpp
MyImageBox::MyImageBox(QWidget *parent) :
    QWidget(parent)
{
     imageLabel = new QLabel();

     scrollArea = new QScrollArea(this);
     scrollArea->setWidget(imageLabel);

     layout = new QGridLayout();
     layout->setContentsMargins(0,0,0,0);
     layout->addWidget(scrollArea);
     setLayout(layout);


}

void MyImageBox::open() {
    QString fileName = QFileDialog::getOpenFileName(this,
                                     "Open File", QDir::currentPath());

     if (!fileName.isEmpty()) {
         QImage image(fileName);
         if (image.isNull()) {
             QMessageBox::information((QWidget*)parent(), "Image Viewer",
                                      QString("Cannot load %1.").arg(fileName));
             return;
         }

         imageLabel->setPixmap(QPixmap::fromImage(image));
         imageLabel->adjustSize();
     }
}

Compile, Debug, Run, Test, Ponies!

Check the status of your source in git and update/commit and push your changes

More References

Getting started with Qt Widgets