KEMBAR78
03 - Qt UI Development | PDF
Qt UI Development



Andreas Jakl
Senior Technical Consultant
Forum Nokia

                              23 October, 2010
                                        v3.2.0
Contents
  – Ways of creating user interfaces with Qt
  – Subclassing Widgets (Signals & Slots, continued)
  – Dialogs
  – Main Window
  – Menus, Toolbars and Actions
User Interfaces with Qt
Qt & Graphics
• Available options
   – Traditional widgets
   – Custom widgets and QPainter
   – QGraphicsView
   – QGLWidget
   – Qt Quick
   – QtWebKit
Traditional Qt Widgets
• QWidget as base of UI components in Qt
   – Window management, layouts
   – Use native UI design
   – Support style sheets
   – Ex.: QPushButton,
      QLabel, QLineEdit
Traditional Qt Widgets
• UI Designer support
   – Instant preview, drag & drop UI
   – Integrated even with translator tool



           High level
           Exactly the same code on all platforms


        Less customization possible, UI effects difficult
        Smaller UI, different paradigms
QWidget and QPainter
• Draw manually using QPainter
   – On QWidget surfaces
   – Flexible painting: text, gradients, polygons,
      bezier curves, transparencies, etc.

           Lets you express your painting directly
           Traditional



        Makes you express your painting directly
QGraphicsView
•   Manage 2D scenes with a scene graph
     – Can manage thousands of items with hierarchies
     – Collision detection, affine transformations,
       drag and drop support
     – Hardware acceleration and integration with QWidget possible


               High level
               Conceptually nice and flexible



           No ready-made common UI components available yet
MeeGo Touch
• UI Framework based on QGraphicsView
   – Provides common UI components with
     theme support
   – Integrates transitions and effects

           Great graphics effects, theme support
           Easy to create smooth UIs
           Already available from source repositories


        Still in development
QGLWidget
     • Very low level
             – Basic setup by Qt
             – You do the hard work                                              Angry Birds and Bounce
                                                                                 by Rovio




                           Complete control over GL
                           Good if you have existing codebase & assets, cross-platform


                      OpenGL is hard work (but there’s more Qt coming for that *)
                      No Qt OpenGL for Symbian integration in Qt 4.7.0
* http://doc.qt.nokia.com/qt3d-snapshot/index.html
Qt Quick
    • Several components
              – QML language and JavaScript
              – Declarative syntax, animations and states integrated
              – Available in Qt 4.7+

                                 Very easy to make slick, fluid UIs
                                 Will soon be most important way to create mobile UIs


                          More tooling is on its way
                          Ready-made UI components on their way *
* Project page: http://bugreports.qt.nokia.com/browse/QTCOMPONENTS
Sample app to integrate web into Qt: http://wiki.forum.nokia.com/index.php/QtWebKitStub



   QtWebKit
   • Open source browser engine
          – Display HTML(5) and JavaScript content
            through a QWidget
          – Combine Qt C++ and web code if needed to
            get best of both worlds

                       Use your existing web skills to create the UI
                       Reuse web components (online help, etc.)


                   Complex UIs and interaction probably more difficult
                   Less performance than native code (but improving)
How to Choose?
• Depends on
   – Complexity of your UI
   – Existing code/assets
   – Experience with low level code
   – Which devices you’re targeting
   – Your timeframe
• Mix and match as appropriate!
Subclassing Widgets
Signal and Slots, Continued
• How to accomplish the following?




    QObject::connect(button, SIGNAL(clicked()),
                     label, SLOT(setText("new text")));

    doesn’t work that way, clicked()-signal doesn’t give required number
      of arguments to setText()-slot.
Custom Widgets (Slots)
• Commonly used: subclass widgets to extend functionality
   – Class MyWindow is a widget (parent)
   – Also manages child widgets
• Widget adds new slot
   – Put text to display into this slot method
      instead of the connect statement
myWindow.h                            myWindow.cpp                               #include <QtGui/QApplication>
                                                                                 #include "MyWindow.h"
 #ifndef MYWINDOW_H                   #include "MyWindow.h"
                                                                                 int main(int argc, char *argv[])
 #define MYWINDOW_H                                                              {
                                      MyWindow::MyWindow(QWidget* parent)            QApplication a(argc, argv);
 #include    <QWidget>                    :                                          MyWindow* window = new MyWindow();
                                                                                     window->show();
 #include    <QVBoxLayout>                QWidget(parent)                            return a.exec();
 #include    <QPushButton>            {                                          }
 #include    <QLabel>                     label = new QLabel("old text");
 #include    <QObject>                    button0 = new QPushButton("Update labels");                            main.cpp
                                          button1 = new QPushButton("Exit");
 class MyWindow : public QWidget
 {                                         layout = new QVBoxLayout(this);
     Q_OBJECT                              layout->addWidget(button0);
 public:                                   layout->addWidget(button1);
     MyWindow(QWidget *parent = 0);        layout->addWidget(label);
                                           setLayout(layout);
 private:
     QLabel* label;                        connect(button0, SIGNAL(clicked()),
     QPushButton* button0;                         this, SLOT(setText()));
     QPushButton* button1;                 connect(button1, SIGNAL(clicked()),
     QVBoxLayout* layout;                          this, SLOT(close()));
                                      }
 private slots:
     void setText();                  void MyWindow::setText()
 };                                   {
                                          label->setText("new text");
 #endif // MYWINDOW_H                 }
Dialogs
Dialogs                                                          QObject               QPaintDevice


•   Dialog is:
                                                                             QWidget
      –   Top-level window
      –   Used for short-term tasks, brief user communication
      –   Can provide return value                                           QDialog
•   Modal
      –   Dialog blocks other application windows (e.g., file open dialog)
      –   Usually called with exec(), returns when dialog is closed
      –   Call with show(): returns immediately, get results via signals
•   Modeless
      –   Operates independently from other windows
          (e.g., find & replace dialog)
      –   Always called with show(): returns immediately
Custom Dialog
  clicked() signal from button in main widget triggers dialog
  Change label in main widget depending on user action selected in dialog
Signals & Slots Diagram
    Signals                               Signals
   clicked()                              clicked()


    Slots                                 Slots

                  Slots      Signals
                 exec(int)
                 accept()    accepted()
                 reject()    rejected()
    Signals                               Signals
   clicked()


    Slots                                  Slots
                                          checkInputDialog()
The Dialog
myDialog.h                         myDialog.cpp
 #ifndef MYDIALOG_H                 #include "mydialog.h"
 #define MYDIALOG_H
                                    MyDialog::MyDialog()
 #include    <QDialog>              {
 #include    <QPushButton>              setFixedSize(150, 100);
 #include    <QVBoxLayout>              QVBoxLayout* vbox = new QVBoxLayout();
 #include    <QLabel>                   QLabel* label = new QLabel("Please confirm.");
                                        QPushButton* okButton = new QPushButton("Ok");
 class MyDialog : public QDialog        QPushButton* cancelButton = new QPushButton("Cancel");
 {
     Q_OBJECT                            // Set the ok button as default
 public:                                 okButton->setDefault(true);
     MyDialog();                         vbox->addWidget(label);
 };                                      vbox->addWidget(okButton);
                                         vbox->addWidget(cancelButton);
 #endif // MYDIALOG_H                    setLayout(vbox);

                                         // Connect the buttons to slots defined by QDialog
                                         connect(okButton, SIGNAL(clicked()),
                                                 this, SLOT(accept()));
                                         connect(cancelButton, SIGNAL(clicked()),
                                                 this, SLOT(reject()));
                                    }
QDialog Base Class
Slot                        Description
virtual void accept()       Hides the dialog and sets the result code to Accepted (1).

virtual void reject()       Hides the dialog and sets the result code to Rejected (0).

virtual void done(int r)    Closes the dialog and sets return value to r.
                            If the dialog is started via exec(), done() causes the event loop to finish, and exec() to return r.
                            Deletes the dialog if Qt::WA_DeleteOnClose is set.
int exec()                  Shows the dialog as a modal dialog, blocking until the user closes it. Returns dialog return value
                            (DialogCode) like Accepted or Rejected.

Signal                      Description
void accepted()             Emitted when dialog has been accepted through calling accept() or done() with the argument
                            QDialog::Accepted
void rejected()             Emitted when dialog has been rejected through calling reject() or done() with the argument
                            QDialog::Rejected
void finished(int result)   Emitted when the dialog’s result code has been set (setResult()) and either accept(), reject() or
                            done() is called.
The Widget
 mywidget.h                            mywidget.cpp
  [...]                                 #include "mywidget.h"

  class MyWidget : public QWidget       MyWidget::MyWidget(QWidget *parent) : QWidget(parent) {
  {                                         setWindowTitle("Main Window - Dialog Example");
      Q_OBJECT                              startButton = new QPushButton("Start dialog");
                                            instructionsLabel = new QLabel("Please push the button");
  public:                                   resultLabel = new QLabel();
      MyWidget(QWidget *parent = 0);
      ~MyWidget();                          layout = new QVBoxLayout(this);
                                            layout->addWidget(instructionsLabel);
  private slots:                            layout->addWidget(startButton);
      void checkInputDialog();              layout->addWidget(resultLabel);

  private:                                  dialog = new MyDialog();
      QPushButton* startButton;
      QLabel* instructionsLabel;            connect(startButton, SIGNAL(clicked()),
      QLabel* resultLabel;                          dialog, SLOT(exec()));
      QVBoxLayout* layout;                  connect(dialog, SIGNAL(accepted()),
      MyDialog* dialog;                             this, SLOT(checkInputDialog()));
                                            connect(dialog, SIGNAL(rejected()),
  };                                                this, SLOT(checkInputDialog()));
                                        }
  #endif // MYWIDGET_H
                                        void MyWidget::checkInputDialog() {
                                            int res = dialog->result(); // Gets result (Accepted/Rejected)
                                            if (res == QDialog::Accepted) {
                                                resultLabel->setText(""Ok" was selected");
                                            } else if (res == QDialog::Rejected) {
                                                resultLabel->setText(""Cancel" was selected");
                                            }
                                        }
Custom Return Values

mydialog.h
 [...]
 private slots:
     void setResult();
 [...]

mydialog.cpp
 [...]
     connect(ignoreButton, SIGNAL(clicked()),
             this, SLOT(setResult()));
 [...]
 void MyDialog::setResult()                     mywidget.cpp
 {
                                                 [...]
     int result = 99;
                                                     connect(dialog, SIGNAL(finished(int)),
     emit done(result);
                                                             this, SLOT(checkInputDialog(int)));
 }
                                                 [...]
                                                 void MyWidget::checkInputDialog(int res)
mywidget.h                                       {
 [...]                                               if (res == 99)
 private slots:                                      {
     void checkInputDialog();                            resultLabel->setText(""Ignore" was selected");
     void checkInputDialog(int);                     }
 [...]                                           }
Predefined Dialogs                         QColorDialog


                            QInputDialog
      QMessageBox




                     QFontDialog
QFileDialog



                                                          QErrorMessage
Predefined Dialogs
• Example: Message box
   – Modal dialog
   – User selection → return value

     int ret = QMessageBox::warning( this, "Exit?",
               "Do you really want to exit the application?",
               QMessageBox::Yes | QMessageBox::No );
Main Window, Menu, Action
Main Window
•   Provides main application window                     Menu Bar
     – Pre-defined layout for standard components                       Toolbars
     – Central widget must be defined, others
                                                                      Dock Widgets
       optional
     – Subclass to create your own implementation
                                                                      Central Widget
•   Differences?
     – Possible with dialog / widgets as well
     – But: more comfortable, consistent and efficient


                                                         Status Bar
Example - QMainWindow
mainwindow.h                                 mainwindow.cpp
  [...]                                       #include "mainwindow.h"

  class MainWindow : public QMainWindow       MainWindow::MainWindow(QWidget *parent, Qt::WFlags flags)
  {                                               : QMainWindow(parent, flags)
      Q_OBJECT                                {
                                                  editor = new QTextEdit();
  public:                                         setMinimumSize(160, 160);
      MainWindow(QWidget *parent = 0,             resize(480, 320);
                Qt::WFlags flags = 0);            setCentralWidget(editor);
      ~MainWindow();                              setWindowTitle("QMainWindow with Menus");

  private:                                        QString message = "Welcome";
      QTextEdit* editor;                          statusBar()->showMessage(message);
                                              }
  [...]
  };

  #endif // MAINWINDOW_H


                    main.cpp is similar to
                    the previous example
Action




                                                                         Image by Anna Cervova
                                                                            (Public Domain)
• Represent abstract user interface           • Stores
  action                                        information about
    – Define once, use in multiple               – Icons
      components                                 – Text
    – Inserted into widgets                      – Keyboard shortcut
        •   Menus
            (can create actions implicitly)
                                                 – Status text
        •   Toolbar buttons                      – “What’s This?” text
        •   Keyboard shortcuts
                                                 – Tooltip
Menu Bar
•   QMenu provides:
     –   a menu widget for menu bars, context menus
         and other popup menus
•   Supports:
     –   Triggered Items
     –   Separators
     –   Submenus
     –   Tear-off menus
•   QMenuBar automatically created by
    QMainWindow
•   QMenu(s) contains individual menu items (
    Actions)
Example – QAction
   mainwindow.h                mainwindow.cpp
    [...]                       [...]
                                    // Create a new “Open” action with an icon, keyboard shortcut and
    class MainWindow                // info-text for the status bar.
        : public QMainWindow        openAct = new QAction("&Open...", this);
    {                               openAct->setIcon(QIcon("images/open.png"));
        Q_OBJECT                    openAct->setShortcut(tr("Ctrl+O"));
    [...]                           openAct->setStatusTip(tr("Open an existing file"));
                                    connect(openAct, SIGNAL(triggered()), this, SLOT(openFile()));
    private slots:
        void openFile();            // Add the action to the menu
                                    fileMenu = menuBar()->addMenu(tr("&File"));
    private:                        fileMenu->addAction(openAct);
        QMenu *fileMenu;
        QAction *openAct;       [...]
    };
                                void MainWindow::openFile()
                                {
                                    // Define two filter options – one for documents, one for all files
                                    // The filter mask is automatically parsed, “;;” separates lines
                                    QString file = QFileDialog::getOpenFileName(this,
                                        "Please choose a file to open", QDir::homePath(),
                                        "Documents (*.pdf *.doc *.docx);;All files (*.*)");

                                    if (!file.isNull())
                                    {
                                        QString info("You chose this filen");
                                        info.append(file);
                                        QMessageBox::information(this, "Your Choice", info, QMessageBox::Ok);
                                    }
                                }
Toolbar
• Same actions as for menu can be used for toolbar
• Default automatically enables drag & drop
Example – QToolBar
   mainwindow.h                mainwindow.cpp
    [...]                       #include "mainwindow.h"

    class MainWindow            MainWindow::MainWindow(QWidget *parent, Qt::WFlags flags)
        : public QMainWindow        : QMainWindow(parent, flags) {
    {                           [...]
        Q_OBJECT                    // Open action
    [...]                           openAct = new QAction("&Open...", this);
                                    openAct->setIcon(QIcon("images/open.png"));
    private:                        openAct->setShortcut(tr("Ctrl+O"));
        QToolBar *toolFile;         openAct->setStatusTip(tr("Open an existing file"));
    };                              connect(openAct, SIGNAL(triggered()), this, SLOT(openFile()));

                                    // Exit action
                                    exitAct = new QAction("E&xit", this);
                                    exitAct->setIcon(QIcon("images/exit.png"));
                                    exitAct->setShortcut(tr("Ctrl+Q"));
                                    exitAct->setStatusTip(tr("Exit the application"));
                                    connect(exitAct, SIGNAL(triggered()), this, SLOT(close()));

                                    // Create the file menu
                                    fileMenu = menuBar()->addMenu(tr("&File"));
                                    fileMenu->addAction(openAct);
                                    fileMenu->addSeparator();
                                    fileMenu->addAction(exitAct);

                                    // Add the actions to the toolbar
                                    toolFile = addToolBar("File");
                                    toolFile->addAction(openAct);
                                    toolFile->addAction(exitAct);
                                [...]
                                }
Thank You.

03 - Qt UI Development

  • 1.
    Qt UI Development AndreasJakl Senior Technical Consultant Forum Nokia 23 October, 2010 v3.2.0
  • 2.
    Contents –Ways of creating user interfaces with Qt – Subclassing Widgets (Signals & Slots, continued) – Dialogs – Main Window – Menus, Toolbars and Actions
  • 3.
  • 4.
    Qt & Graphics •Available options – Traditional widgets – Custom widgets and QPainter – QGraphicsView – QGLWidget – Qt Quick – QtWebKit
  • 5.
    Traditional Qt Widgets •QWidget as base of UI components in Qt – Window management, layouts – Use native UI design – Support style sheets – Ex.: QPushButton, QLabel, QLineEdit
  • 6.
    Traditional Qt Widgets •UI Designer support – Instant preview, drag & drop UI – Integrated even with translator tool High level Exactly the same code on all platforms Less customization possible, UI effects difficult Smaller UI, different paradigms
  • 7.
    QWidget and QPainter •Draw manually using QPainter – On QWidget surfaces – Flexible painting: text, gradients, polygons, bezier curves, transparencies, etc. Lets you express your painting directly Traditional Makes you express your painting directly
  • 8.
    QGraphicsView • Manage 2D scenes with a scene graph – Can manage thousands of items with hierarchies – Collision detection, affine transformations, drag and drop support – Hardware acceleration and integration with QWidget possible High level Conceptually nice and flexible No ready-made common UI components available yet
  • 9.
    MeeGo Touch • UIFramework based on QGraphicsView – Provides common UI components with theme support – Integrates transitions and effects Great graphics effects, theme support Easy to create smooth UIs Already available from source repositories Still in development
  • 10.
    QGLWidget • Very low level – Basic setup by Qt – You do the hard work Angry Birds and Bounce by Rovio Complete control over GL Good if you have existing codebase & assets, cross-platform OpenGL is hard work (but there’s more Qt coming for that *) No Qt OpenGL for Symbian integration in Qt 4.7.0 * http://doc.qt.nokia.com/qt3d-snapshot/index.html
  • 11.
    Qt Quick • Several components – QML language and JavaScript – Declarative syntax, animations and states integrated – Available in Qt 4.7+ Very easy to make slick, fluid UIs Will soon be most important way to create mobile UIs More tooling is on its way Ready-made UI components on their way * * Project page: http://bugreports.qt.nokia.com/browse/QTCOMPONENTS
  • 12.
    Sample app tointegrate web into Qt: http://wiki.forum.nokia.com/index.php/QtWebKitStub QtWebKit • Open source browser engine – Display HTML(5) and JavaScript content through a QWidget – Combine Qt C++ and web code if needed to get best of both worlds Use your existing web skills to create the UI Reuse web components (online help, etc.) Complex UIs and interaction probably more difficult Less performance than native code (but improving)
  • 13.
    How to Choose? •Depends on – Complexity of your UI – Existing code/assets – Experience with low level code – Which devices you’re targeting – Your timeframe • Mix and match as appropriate!
  • 14.
  • 15.
    Signal and Slots,Continued • How to accomplish the following? QObject::connect(button, SIGNAL(clicked()), label, SLOT(setText("new text")));  doesn’t work that way, clicked()-signal doesn’t give required number of arguments to setText()-slot.
  • 16.
    Custom Widgets (Slots) •Commonly used: subclass widgets to extend functionality – Class MyWindow is a widget (parent) – Also manages child widgets • Widget adds new slot – Put text to display into this slot method instead of the connect statement
  • 17.
    myWindow.h myWindow.cpp #include <QtGui/QApplication> #include "MyWindow.h" #ifndef MYWINDOW_H #include "MyWindow.h" int main(int argc, char *argv[]) #define MYWINDOW_H { MyWindow::MyWindow(QWidget* parent) QApplication a(argc, argv); #include <QWidget> : MyWindow* window = new MyWindow(); window->show(); #include <QVBoxLayout> QWidget(parent) return a.exec(); #include <QPushButton> { } #include <QLabel> label = new QLabel("old text"); #include <QObject> button0 = new QPushButton("Update labels"); main.cpp button1 = new QPushButton("Exit"); class MyWindow : public QWidget { layout = new QVBoxLayout(this); Q_OBJECT layout->addWidget(button0); public: layout->addWidget(button1); MyWindow(QWidget *parent = 0); layout->addWidget(label); setLayout(layout); private: QLabel* label; connect(button0, SIGNAL(clicked()), QPushButton* button0; this, SLOT(setText())); QPushButton* button1; connect(button1, SIGNAL(clicked()), QVBoxLayout* layout; this, SLOT(close())); } private slots: void setText(); void MyWindow::setText() }; { label->setText("new text"); #endif // MYWINDOW_H }
  • 18.
  • 19.
    Dialogs QObject QPaintDevice • Dialog is: QWidget – Top-level window – Used for short-term tasks, brief user communication – Can provide return value QDialog • Modal – Dialog blocks other application windows (e.g., file open dialog) – Usually called with exec(), returns when dialog is closed – Call with show(): returns immediately, get results via signals • Modeless – Operates independently from other windows (e.g., find & replace dialog) – Always called with show(): returns immediately
  • 20.
    Custom Dialog clicked() signal from button in main widget triggers dialog Change label in main widget depending on user action selected in dialog
  • 21.
    Signals & SlotsDiagram Signals Signals clicked() clicked() Slots Slots Slots Signals exec(int) accept() accepted() reject() rejected() Signals Signals clicked() Slots Slots checkInputDialog()
  • 22.
    The Dialog myDialog.h myDialog.cpp #ifndef MYDIALOG_H #include "mydialog.h" #define MYDIALOG_H MyDialog::MyDialog() #include <QDialog> { #include <QPushButton> setFixedSize(150, 100); #include <QVBoxLayout> QVBoxLayout* vbox = new QVBoxLayout(); #include <QLabel> QLabel* label = new QLabel("Please confirm."); QPushButton* okButton = new QPushButton("Ok"); class MyDialog : public QDialog QPushButton* cancelButton = new QPushButton("Cancel"); { Q_OBJECT // Set the ok button as default public: okButton->setDefault(true); MyDialog(); vbox->addWidget(label); }; vbox->addWidget(okButton); vbox->addWidget(cancelButton); #endif // MYDIALOG_H setLayout(vbox); // Connect the buttons to slots defined by QDialog connect(okButton, SIGNAL(clicked()), this, SLOT(accept())); connect(cancelButton, SIGNAL(clicked()), this, SLOT(reject())); }
  • 23.
    QDialog Base Class Slot Description virtual void accept() Hides the dialog and sets the result code to Accepted (1). virtual void reject() Hides the dialog and sets the result code to Rejected (0). virtual void done(int r) Closes the dialog and sets return value to r. If the dialog is started via exec(), done() causes the event loop to finish, and exec() to return r. Deletes the dialog if Qt::WA_DeleteOnClose is set. int exec() Shows the dialog as a modal dialog, blocking until the user closes it. Returns dialog return value (DialogCode) like Accepted or Rejected. Signal Description void accepted() Emitted when dialog has been accepted through calling accept() or done() with the argument QDialog::Accepted void rejected() Emitted when dialog has been rejected through calling reject() or done() with the argument QDialog::Rejected void finished(int result) Emitted when the dialog’s result code has been set (setResult()) and either accept(), reject() or done() is called.
  • 24.
    The Widget mywidget.h mywidget.cpp [...] #include "mywidget.h" class MyWidget : public QWidget MyWidget::MyWidget(QWidget *parent) : QWidget(parent) { { setWindowTitle("Main Window - Dialog Example"); Q_OBJECT startButton = new QPushButton("Start dialog"); instructionsLabel = new QLabel("Please push the button"); public: resultLabel = new QLabel(); MyWidget(QWidget *parent = 0); ~MyWidget(); layout = new QVBoxLayout(this); layout->addWidget(instructionsLabel); private slots: layout->addWidget(startButton); void checkInputDialog(); layout->addWidget(resultLabel); private: dialog = new MyDialog(); QPushButton* startButton; QLabel* instructionsLabel; connect(startButton, SIGNAL(clicked()), QLabel* resultLabel; dialog, SLOT(exec())); QVBoxLayout* layout; connect(dialog, SIGNAL(accepted()), MyDialog* dialog; this, SLOT(checkInputDialog())); connect(dialog, SIGNAL(rejected()), }; this, SLOT(checkInputDialog())); } #endif // MYWIDGET_H void MyWidget::checkInputDialog() { int res = dialog->result(); // Gets result (Accepted/Rejected) if (res == QDialog::Accepted) { resultLabel->setText(""Ok" was selected"); } else if (res == QDialog::Rejected) { resultLabel->setText(""Cancel" was selected"); } }
  • 25.
    Custom Return Values mydialog.h [...] private slots: void setResult(); [...] mydialog.cpp [...] connect(ignoreButton, SIGNAL(clicked()), this, SLOT(setResult())); [...] void MyDialog::setResult() mywidget.cpp { [...] int result = 99; connect(dialog, SIGNAL(finished(int)), emit done(result); this, SLOT(checkInputDialog(int))); } [...] void MyWidget::checkInputDialog(int res) mywidget.h { [...] if (res == 99) private slots: { void checkInputDialog(); resultLabel->setText(""Ignore" was selected"); void checkInputDialog(int); } [...] }
  • 26.
    Predefined Dialogs QColorDialog QInputDialog QMessageBox QFontDialog QFileDialog QErrorMessage
  • 27.
    Predefined Dialogs • Example:Message box – Modal dialog – User selection → return value int ret = QMessageBox::warning( this, "Exit?", "Do you really want to exit the application?", QMessageBox::Yes | QMessageBox::No );
  • 28.
  • 29.
    Main Window • Provides main application window Menu Bar – Pre-defined layout for standard components Toolbars – Central widget must be defined, others Dock Widgets optional – Subclass to create your own implementation Central Widget • Differences? – Possible with dialog / widgets as well – But: more comfortable, consistent and efficient Status Bar
  • 30.
    Example - QMainWindow mainwindow.h mainwindow.cpp [...] #include "mainwindow.h" class MainWindow : public QMainWindow MainWindow::MainWindow(QWidget *parent, Qt::WFlags flags) { : QMainWindow(parent, flags) Q_OBJECT { editor = new QTextEdit(); public: setMinimumSize(160, 160); MainWindow(QWidget *parent = 0, resize(480, 320); Qt::WFlags flags = 0); setCentralWidget(editor); ~MainWindow(); setWindowTitle("QMainWindow with Menus"); private: QString message = "Welcome"; QTextEdit* editor; statusBar()->showMessage(message); } [...] }; #endif // MAINWINDOW_H main.cpp is similar to the previous example
  • 31.
    Action Image by Anna Cervova (Public Domain) • Represent abstract user interface • Stores action information about – Define once, use in multiple – Icons components – Text – Inserted into widgets – Keyboard shortcut • Menus (can create actions implicitly) – Status text • Toolbar buttons – “What’s This?” text • Keyboard shortcuts – Tooltip
  • 32.
    Menu Bar • QMenu provides: – a menu widget for menu bars, context menus and other popup menus • Supports: – Triggered Items – Separators – Submenus – Tear-off menus • QMenuBar automatically created by QMainWindow • QMenu(s) contains individual menu items ( Actions)
  • 33.
    Example – QAction mainwindow.h mainwindow.cpp [...] [...] // Create a new “Open” action with an icon, keyboard shortcut and class MainWindow // info-text for the status bar. : public QMainWindow openAct = new QAction("&Open...", this); { openAct->setIcon(QIcon("images/open.png")); Q_OBJECT openAct->setShortcut(tr("Ctrl+O")); [...] openAct->setStatusTip(tr("Open an existing file")); connect(openAct, SIGNAL(triggered()), this, SLOT(openFile())); private slots: void openFile(); // Add the action to the menu fileMenu = menuBar()->addMenu(tr("&File")); private: fileMenu->addAction(openAct); QMenu *fileMenu; QAction *openAct; [...] }; void MainWindow::openFile() { // Define two filter options – one for documents, one for all files // The filter mask is automatically parsed, “;;” separates lines QString file = QFileDialog::getOpenFileName(this, "Please choose a file to open", QDir::homePath(), "Documents (*.pdf *.doc *.docx);;All files (*.*)"); if (!file.isNull()) { QString info("You chose this filen"); info.append(file); QMessageBox::information(this, "Your Choice", info, QMessageBox::Ok); } }
  • 34.
    Toolbar • Same actionsas for menu can be used for toolbar • Default automatically enables drag & drop
  • 35.
    Example – QToolBar mainwindow.h mainwindow.cpp [...] #include "mainwindow.h" class MainWindow MainWindow::MainWindow(QWidget *parent, Qt::WFlags flags) : public QMainWindow : QMainWindow(parent, flags) { { [...] Q_OBJECT // Open action [...] openAct = new QAction("&Open...", this); openAct->setIcon(QIcon("images/open.png")); private: openAct->setShortcut(tr("Ctrl+O")); QToolBar *toolFile; openAct->setStatusTip(tr("Open an existing file")); }; connect(openAct, SIGNAL(triggered()), this, SLOT(openFile())); // Exit action exitAct = new QAction("E&xit", this); exitAct->setIcon(QIcon("images/exit.png")); exitAct->setShortcut(tr("Ctrl+Q")); exitAct->setStatusTip(tr("Exit the application")); connect(exitAct, SIGNAL(triggered()), this, SLOT(close())); // Create the file menu fileMenu = menuBar()->addMenu(tr("&File")); fileMenu->addAction(openAct); fileMenu->addSeparator(); fileMenu->addAction(exitAct); // Add the actions to the toolbar toolFile = addToolBar("File"); toolFile->addAction(openAct); toolFile->addAction(exitAct); [...] }
  • 36.