Meeting 09: Introduction to Qt

The goal of today's meeting it to learn about a popular cross-platform library called Qt. Qt is most well-known as a graphical user interface (GUI) library although it has many other components. You can find the instructions for installing this on your host system here. Please do this before class.

Today we will look at the basics of the Qt Widgets library.

Links:

Exercise 09: Basic Qt Examples

GitHub Invitation URL: exercise09

Steps:

  1. Clone the assignment for today after accepting the GitHub invitation at the link above and waiting for the repository to be imported. The repository is initially empty except for a simple readme file.

  2. Create a C++ source file named hello_static.cpp in the top-level directory of the repository with the following contents.

     #include <QApplication>
     #include <QLabel>
    
     int main(int argc, char *argv[]){
       QApplication app(argc, argv);
    
       QLabel hello("Hello World!");
    
       hello.show();
       return app.exec();
    }
  3. Create a CMakeLists.txt file in the top-level directory of the repository with the following contents

    cmake_minimum_required(VERSION 3.5)
    project(QtHello)
    
    set(CMAKE_AUTOMOC ON)
    set(CMAKE_INCLUDE_CURRENT_DIR ON)
    find_package(Qt5Widgets REQUIRED)
    
    add_executable(hello_static hello_static.cpp)
    target_link_libraries(hello_static Qt5::Widgets)
  4. Build and run your hello_static application.

  5. Create a header file named label_printer.h in the top-level directory of the repository with the following contents

    #ifndef LABEL_PRINTER_H
    #define LABEL_PRINTER_H
    
    #include <QLabel>
    
    class LabelPrinter: public QLabel
    {
    Q_OBJECT
    public:
    
      LabelPrinter(const char * labelstr);
    
      void keyPressEvent(QKeyEvent *ev);  
    };
    
    #endif

    and an implementation file label_printer.cpp with the contents

    #include "label_printer.h"
    
    #include <QDebug>
    
    LabelPrinter::LabelPrinter(const char * labelstr): QLabel(labelstr) {};
    
    void LabelPrinter::keyPressEvent(QKeyEvent *ev){
      qDebug() << "Hello World!";
    }
  6. Create a C++ source file named hello_label.cpp in the top-level directory of the repository with the following contents.

    #include <QApplication>
    
    #include "label_printer.h"
    
    int main(int argc, char *argv[])
    {
      QApplication app(argc, argv);
    
      LabelPrinter hello("Hello world!");
    
      hello.show();
      return app.exec();
    }
  7. Add the necessary syntax to the CMakeLists.txt file to build the hello_label executable.

  8. Build and run the hello_label executable. Click in the window and type at the keyboard. What happens in the console?

  9. Now, add and commit the source files (including the CMakeLists.txt) to the local repository.

  10. Finally, use git push to synchronize the repository with that on GitHub.

You have completed the Exercise.