0% found this document useful (0 votes)
111 views24 pages

QT Cheat

Uploaded by

ysfnlyzc61
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
111 views24 pages

QT Cheat

Uploaded by

ysfnlyzc61
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

QT

 Book  in  the  Library    

QT  Programming  

E-­‐kitaplar  (e-­‐books)   Safari  IT  Books  

Search  qt  
Read:        C++  GUI  Programming  with  Qt-­‐4  

GUI  Programming   HELLO    QT  Program  


• GUI  programs  use  event  driven  programming  model:  
– GUI  programs  have  a  lot  of  interacKvity:  there  are  many  inputs  that  may   #include <QApplication>!
come  in  different  forms  (mouse  clicks,  buNon  clicks,  drawing  etc.  )    
#include <QLabel>!
– A  style  of  coding  where  a  program's  overall  flow  of  execuKon  is  dictated  
by  events.   !
– The  program  loads,  creates  visual/non-­‐visual  objects  and  then  waits  for   int main(int argc, char *argv[])!
user  input  events.   {!
– As  each  event  occurs,  the  program  runs  parKcular  code  to  respond.   int rc ; !
QApplication app(argc, argv);!
• Control  flows  of  GUI  programs  have  the  following  paNern     QLabel label("Hello Qt!");!
!
set-up, creation, configuration of objects (visual or non-visual)
label.show();!
do {! !
event = GetNextEvent() ;! rc = app.exec();!
process event ! return(rc) ;!
} while (event != quit);!
}!
QApplicaKon  Object   Compiling  Hello  QT  Program    
• The  QApplicaKon  class  manages  the  GUI  applicaKon's  control  flow  and  main   • Put  your  code  in  a  directory  (there  should  be  
seXngs.  
• QApplicaKon  specializes  GUI  applicaKon  with  some  funcKonality  needed  for  
no  other  non-­‐project  related  files/codes  
widget-­‐based  applicaKons.  It  handles  widget  specific  iniKalizaKon,  finalizaKon.   there)  
 
• For  any  GUI  applicaKon  using  Qt,  there  is  precisely  one  QApplicaKon  object,  no  
maNer  whether  the  applicaKon  has  0,  1,  2  or  more  windows  at  any  given  Kme.  For  
 
non-­‐widget  based  Qt  applicaKons,  use  QCoreApplicaKon  instead,  as  it  does  not   >qmake –project!
depend  on  the  widgets  library.  
>qmake HELLO.pro! <———— This command will create a Makefile automatically

• Widget  :  visual  element  (object)   >make!

BUTTON  Example  
Signals  and  Slots    
The  connect()  statement:  
 
connect(sender,  SIGNAL(signal),  receiver,  SLOT(slot));  
#include <QApplication>!
#include <QPushButton>!
!
int main(int argc, char *argv[])!
{!
QApplication app(argc, argv);!
!
QPushButton *button = new QPushButton(”Quit");!
QObject::connect(button, SIGNAL(clicked()),!
&app, SLOT(quit()));!
button->show();!
!
return app.exec();!
}!
SLIDER  Example  
SLIDER  Example  Code  

#include  <QApplicaKon>    
#include  <QHBoxLayout>            QObject::connect(spinBox,  SIGNAL(valueChanged(int)),  
#include  <QSlider>                                              slider,  SLOT(setValue(int)));  
#include  <QSpinBox>            QObject::connect(slider,  SIGNAL(valueChanged(int)),  
                                             spinBox,  SLOT(setValue(int)));  
int  main(int  argc,  char  *argv[])            spinBox-­‐>setValue(35);  
{    
QSlider              QApplicaKon  app(argc,  argv);            QHBoxLayout  *layout  =  new  QHBoxLayout;  
QSpinBox  
           layout-­‐>addWidget(spinBox);  
           QWidget  *window  =  new  QWidget;            layout-­‐>addWidget(slider);  
           window-­‐>setWindowTitle("Enter  Your  Age");            window-­‐>setLayout(layout);  
   
         QSpinBox  *spinBox  =  new  QSpinBox;            window-­‐>show();  
         QSlider  *slider  =  new  QSlider(Qt::Horizontal);    
         spinBox-­‐>setRange(0,  130);            return  app.exec();  
         slider-­‐>setRange(0,  130);   }  
   
             

Signals  and  Slots     Signals  and  Slots    


Signals  and  Slots     Signals  and  Slots    

Inheritance  Tree  for  the  QT  Classes  


seen  so  far  (parKal)  

QT  Programming  
QT  Creator    (IDE)   Sub-­‐Classing  
• For  qt  development,  use  Qt  Creator  IDE  
       h>ps://www.qt.io/ide/   • To  customize  widgets,  we  can  pass  parameters  or  call  methods  to  
  modify    appearance  and  behaviour.  
  • If  these  are  not  sufficient  or  are  not  available  for    specific  
  customizaDons,  we  can    subclass  exisDng  classes  to  create  
customized    or  new  widgets.    
 
 
ExisDng  Qt  class  
 
 
 
 
• Or  alternaDvely,  command  line    tools  like  qmake  
New  Qt  class  with  new  methods,    
signals,  slots  etc.    

Sub-­‐classing  QDialog   Sub-­‐classing  QDialog  


• FindDialog’s  parent-­‐child  relaDonship      
Sub-­‐classing  QDialog   Sub-­‐classing  QDialog  
QDialog   • main.c      (main  program  using  FindDialog)  

#include  <QApplicaDon>  
#include  "finddialog.h"  
 
 
FindDialog     int  main(int  argc,  char  *argv[])  
 {  
         QApplicaDon  app(argc,  argv);  
         FindDialog  *dialog  =  new  FindDialog;  
         dialog-­‐>show();  
For  newly  created  sub-­‐class  (FindDialog),  prepare  two  source  codes  files:            return  app.exec();  
  }  
FindDialog.h!
!
FindDialog.cpp !

Sub-­‐classing  Qdialog   Sub-­‐classing  Qdialog  


finddialog.h    file   finddialog.cpp    file  
#ifndef  FINDDIALOG_H   signals:   #include  <QtGui>  
#define  FINDDIALOG_H        void  findNext(const  QString  &str,   #include  "finddialog.h"  
 
  Qt::CaseSensiDvity  cs);  
FindDialog::FindDialog(QWidget  *parent)  :  QDialog(parent)  
#include  <QDialog>        void  findPrevious(const  QString  &str,   {  
  Qt::CaseSensiDvity  cs);            label  =  new  QLabel(tr("Find  &what:"));  
class  QCheckBox;              lineEdit  =  new  QLineEdit;  
         label-­‐>setBuddy(lineEdit);  
class  QLabel;   private  slots:    
class  QLineEdit;            void  findClicked();            caseCheckBox  =  new  QCheckBox(tr("Match  &case"));  
class  QPushBu>on;          void  enableFindBu>on(const  QString  &text);            backwardCheckBox  =  new  QCheckBox(tr("Search  &backward"));  
 
   
         findBu>on  =  new  QPushBu>on(tr("&Find"));  
class  FindDialog  :  public  QDialog    private:            findBu>on-­‐>setDefault(true);  
{          QLabel  *label;            findBu>on-­‐>setEnabled(false);  
       Q_OBJECT          QLineEdit  *lineEdit;            closeBu>on  =  new  QPushBu>on(tr("Close"));  
 
         QCheckBox  *caseCheckBox;            connect(lineEdit,  SIGNAL(textChanged(const  QString  &)),  
 public:          QCheckBox  *backwardCheckBox;                        this,  SLOT(enableFindBu>on(const  QString  &)));  
         FindDialog(QWidget  *parent  =  0);          QPushBu>on  *findBu>on;            connect(findBu>on,  SIGNAL(clicked()),  
                     this,  SLOT(findClicked()));  
         QPushBu>on  *closeBu>on;  
         connect(closeBu>on,  SIGNAL(clicked()),  
};                        this,  SLOT(close()));  
#endif  
Sub-­‐classing  Qdialog   Sub-­‐classing  Qdialog  
finddialog.cpp    file   finddialog.cpp    file  
#include  <QtGui>    QHBoxLayout  *topLehLayout  =  new  QHBoxLayout;  
#include  "finddialog.h"          topLehLayout-­‐>addWidget(label);  
         topLehLayout-­‐>addWidget(lineEdit);   void  FindDialog::findClicked()  
FindDialog::FindDialog(QWidget  *parent)  :  QDialog(parent)      {  
{          QVBoxLayout  *lehLayout  =  new  QVBoxLayout;            QString  text  =  lineEdit-­‐>text();  
         label  =  new  QLabel(tr("Find  &what:"));          lehLayout-­‐>addLayout(topLehLayout);            Qt::CaseSensiDvity  cs  =  
         lineEdit  =  new  QLineEdit;          lehLayout-­‐>addWidget(caseCheckBox);                            caseCheckBox-­‐>isChecked()  ?  Qt::CaseSensiDve  
         label-­‐>setBuddy(lineEdit);          lehLayout-­‐>addWidget(backwardCheckBox);                                                                                :  Qt::CaseInsensiDve;  
             if  (backwardCheckBox-­‐>isChecked())  {  
         caseCheckBox  =  new  QCheckBox(tr("Match  &case"));          QVBoxLayout  *rightLayout  =  new  QVBoxLayout;                    emit  findPrevious(text,  cs);  
         backwardCheckBox  =  new  QCheckBox(tr("Search  &backward"));          rightLayout-­‐>addWidget(findBu>on);            }  else  {  
         rightLayout-­‐>addWidget(closeBu>on);                    emit  findNext(text,  cs);  
         findBu>on  =  new  QPushBu>on(tr("&Find"));          rightLayout-­‐>addStretch();            }  
         findBu>on-­‐>setDefault(true);      }  
         findBu>on-­‐>setEnabled(false);          QHBoxLayout  *mainLayout  =  new  QHBoxLayout;    
         closeBu>on  =  new  QPushBu>on(tr("Close"));          mainLayout-­‐>addLayout(lehLayout);   void  FindDialog::enableFindBu>on(const  QString  &text)  
         mainLayout-­‐>addLayout(rightLayout);    {  
         connect(lineEdit,  SIGNAL(textChanged(const  QString  &)),          setLayout(mainLayout);            findBu>on-­‐>setEnabled(!text.isEmpty());  
                     this,  SLOT(enableFindBu>on(const  QString  &)));      }  
         connect(findBu>on,  SIGNAL(clicked()),                  setWindowTitle(tr("Find"));  
                     this,  SLOT(findClicked()));          setFixedHeight(sizeHint().height());  
         connect(closeBu>on,  SIGNAL(clicked()),    }  
                     this,  SLOT(close()));    

QT  Designer   Form  Designed  with    


• Qt  Designer  is  Qt's  tool  for  designing  and  building  graphical  user  interfaces  (GUIs)  
from  Qt  components.    
QT  Designer  
• You  can  compose  and  customize  your  widgets  or  dialogs  in  a  what-­‐you-­‐see-­‐is-­‐
what-­‐you-­‐get  (WYSIWYG)  manner,  and  test  them  using  different  styles  and  
resoluDons.  
What is QT?
Qt is a free and open-source widget toolkit for creating graphical user interfaces
PS11: QT Programming as well as cross-platform applications that run on various software and hardware
platforms such as Linux, Windows, macOS, Android or embedded systems with
little or no change in the underlying codebase while still being a native application
with native capabilities and speed.

CMPE 230 - Spring 2024

Based on the slides by Abdullatif Köksal, with his permission.

1. https://en.wikipedia.org/wiki/Qt_(software)

How to install QT on Ubuntu QT Modules


● QT’s website
● Terminal
sudo apt-get install build-essential

sudo apt install -y qtcreator qtbase5-dev qt5-qmake cmake

1. https://en.wikipedia.org/wiki/Qt_(software)
1. Hello World Example 1. Hello World Example
Our objective is to Add Desktop kit for
create a simple GUI desktop applications.
application with a label
and a quit button which
are aligned horizontally. Note that C++ compiler
might be different.

Let’s start with an empty


qmake project.

1. Hello World Example .pro File


It will create our project Project files contain all the information required by qmake to build your application, library, or
plugin. Generally, you use series of declarations to specify the resources in the project, but
with only .pro file. support for simple programming constructs enables you to describe different build processes
for different platforms and environments.

We will use project files to add source and header files (it will be done automatically) and to
declare required QT Libraries.

1. https://doc.qt.io/qt-5/qmake-project-files.html
1. Hello World Example 1. Hello World Example
Let’s create a C++ file It’s added to project file
for our main window. automatically.

QApplication .pro File


It handles widget We have to add
specific initialization, QT += widgets
finalization. to our project file.
For any GUI application
using Qt, there is precisely
one QApplication object,
no matter whether the
application has 0, 1, 2 or
more windows at any
given time.

1. https://doc.qt.io/qt-5/qapplication.html 1. https://doc.qt.io/qt-5/qapplication.html
.cpp File 1. Hello World Example
And our simple main And our simple main
file: file:

We can run our


application but there
will be no element in it.

1. https://doc.qt.io/qt-5/qapplication.html 1. https://doc.qt.io/qt-5/qapplication.html

1. Hello World Example 1. Hello World Example


Let’s add Our program would
QMainWindow class for look like this. It has
common needs of a already OS specific
main window which design which has quit,
include status bar, minimize, and full-
toolbar, and menu bar. screen buttons.
1. Hello World Example 1. Hello World Example
Let’s add a label that Now we have to add button
says this is our first which will be aligned
project and add it as horizontally with our label.
our central widget to So, we have to add
QHBoxLayout first as our
mainwindow.
central widget.

cw is our central widget


and the parent of hl. QLabel
is added as a widget to hl.

1. Hello World Example 1. Hello World Example


Let’s add the button to We have a label and a
QHBoxLayout with its name button that are aligned
in initialization. horizontally in the center of
main window. However, we
didn’t add any functionality
to button right now.
Signals and Slots connect
Signals: We can use connect
Signals are emitted by an object when its internal statement to connect
state has changed in some way that might be
interesting to the object's client or owner. signals and slots for wanted
Slots: action.
A slot is called when a signal connected to it is
emitted. Slots are normal C++ functions and can
be called normally; their only special feature is
that signals can be connected to them.

1. https://doc.qt.io/qt-5/signalsandslots.html

1. Hello World Example 2. Color Game


Let’s connect our button’s We will build a color game with timer. We would have 4x3 colors, randomly
clicked signal to app’s quit initialized between Blue, Green, and Red. When you click one of them, the color
slot. would set again randomly. Your objective is to make all colors same under 30
seconds. We will see:
● QGridLayout
● QVBoxLayout, QHBoxLayout
● QTimer
● QSpacerItem
● QMessageBox
● Custom Widgets and Layouts
2. Color Game QTimer
Let’s start with some assumptions before coding. Let’s start with the QTimer
object.
1. We will use a widget as main window instead of
QMainWindow. ● Timeout signal will be send
2. We would have timer label and grid layout in a based on decided interval
vertical box layout. (generally with 1 seconds =
3. We would write custom buttons with colors. 1000 milliseconds)
4. We would write custom widget class for timer ● We will change the label in
with labels. each signal, so add a slot
5. We would write custom grid layout which checks according to this with a
colors of all color buttons. counter.

1. https://doc.qt.io/qt-5/qtimer.html#details

2. Color Game 2. Color Game


Add a custom timer class with: Constructor sets label, counter,
and timer.
● QTimer to detect seconds
● int counter to count
● QLabel to add it into layout
We add a connection
● MyTimerSlot to change
MyTimerSlot() for 1000 ms
QLabel in each tick.
timeout signal.
● We will use message box to
declare failure when the
timer hits 30.
2. Color Game 2. Color Game
MyTimerSlot: Let’s talk about our custom
color button which inherits
● Sets counter in each tick.
from QPushButton.
● Changes label according to
counter. ● Constructor with color
● If counter is greater than or name, text, and parent
equal to 30, in other words ● Color name field
30 seconds passed, it ● Slot to change color
raises a message box and randomly
stops timer.

2. Color Game 2. Color Game


Important notes: The constructor:

Q_OBJECT statement is necessary to 1. We call constructor


add custom slots. method of QPushButton.
2. Set color based on the
color string.
When you add Q_OBJECT, you have
to run qmake in your QT Creator to
avoid any problems!
2. Color Game 2. Color Game
Change color slot: 1. Now, we have to design
QGridLayout. We can put mxn items
1. First, create a random in Grid Layout. We will put color
integer to detect color. buttons in 4x3 cells.
2. Set color based on this 2. We have to add a pointer to our
randomization. timer object to stop it when we
match all colors.
3. We also have to check color
buttons in this grid layout whether
P.S.: These functions could
they have same colors or not in
have improved with helper each click. So we design it as slots.
functions.

2. Color Game 2. Color Game


The constructor can be implemented in a straightforward way. To check colors, first we
implement a very basic logic. Two
We call constructor of QGridLayout and add a pointer to timer object.
important things:

1. We check widgets in
GridLayout.
2. Then, typecast to
ColorButton as we know all
widgets are ColorButtons.

Then, we set a message box if all


colors are same.
2. Color Game 2. Color Game
Now, we can implement our main Then, we initialized color buttons
window and general logic with with random colors.
the help of these classes.
We added two connections, both
Our main window is a widget. We of them is triggered with clicked
defined our custom timer and signal in color button:
custom grid layouts.
● change_color slot in
ColorButton is called.
● check_colors slot in
GridLayout is called.

2. Color Game 2. Color Game


Finally, we added color button to Then, we add widgets and
grid layout based on row and layouts to vertical box with spacer
column indices with 1 span. item.

Spacer item expands to add


additional space horizontally and
vertically.
2. Color Game 2. Color Game
Finally, the design looks like this: Finally, the design looks like this:

Example gif for winning scenario


(it is speeded-up)

2. Color Game QT on terminal


Finally, the design looks like this: ● Existing project

Example gif for losing scenario (it qmake -makefile


is speeded-up) make

● New project
qmake -project // create an qmake project file
qmake // create a "Makefile" which contains the rules to build your application
make
Ex2

Any questions?
Conclusion
Code
// I n c l u d e n e c e s s a r y Qt h e a d e r s
#include <QApplication >
#include <QPushButton>
#include <QButtonGroup>
#include <QLCDNumber>
#include <QHBoxLayout>

int main ( int argc , char ∗ argv [ ] )


{
// I n i t i a l i z e t h e Qt a p p l i c a t i o n
Q A p p l i c a t i o n app ( argc , argv ) ;

QWidget window ; // Main a p p l i c a t i o n window


QButtonGroup buttongroup ; // Group t o manage b u t t o n i n t e r a c t i o n s
QPushButton ∗ button [ 2 ] ; // Array t o h o l d two b u t t o n s
QHBoxLayout layout ; // Horizontal l a y o u t to arrange widgets
QLCDNumber disp ; // LCD number d i s p l a y
QString s ; // String to hold button l a b e l s

// C r ea t e and c o n f i g u r e b u t t o n s
f or ( int i = 0 ; i < 2 ; i ++) {
s = QString : : number ( i +1); // Convert i n t e g e r t o s t r i n g
button [ i ] = new QPushButton ( s ) ; // C r ea t e new b u t t o n w i t h l a b e l
l a y o u t . addWidget ( button [ i ] ) ; // Add b u t t o n t o l a y o u t
buttongroup . addButton ( button [ i ] , i +1); // Add b u t t o n t o group w i t h ID
}

// Connect b u t t o n group s i g n a l t o LCD d i s p l a y s l o t


QObject : : c o n n e c t (& buttongroup , SIGNAL( b u t t o n C l i c k e d ( int ) ) ,
&d i s p , SLOT( d i s p l a y ( int ) ) ) ;

// Add LCD d i s p l a y t o l a y o u t
l a y o u t . addWidget(& d i s p ) ;

// S e t l a y o u t f o r t h e main window and show i t


window . s e t L a y o u t (& l a y o u t ) ;
window . show ( ) ;
We have seen QT Creator and several QT widgets with examples.

// E x e c u t e t h e a p p l i c a t i o n
return app . e x e c ( ) ;
}

Button Image

QT Button Example

Code
#include <QApplication >
Note #include <QPushButton>

This Qt application creates a simple interface with two buttons and an LCD number display. The buttons are labeled ”1” and int main ( int argc , char ∗ argv [ ] )
”2”. When either button is clicked, the corresponding number is displayed on the LCD. The application uses a ‘QButtonGroup‘ {
to manage the buttons and connects the button click signal to the ‘display(int)‘ slot of the ‘QLCDNumber‘ display. Q A p p l i c a t i o n app ( argc , argv ) ;

QPushButton ∗ button = new QPushButton ( ” H e l l o ” ) ;


QObject : : c o n n e c t ( button , SIGNAL( c l i c k e d ( ) ) ,
&app , SLOT( q u i t ( ) ) ) ;
button−>show ( ) ;

return app . e x e c ( ) ;
}

Button Image

Note
When the button is clicked, it terminates the application.

2 1
2022 Problem 4 QT Spinslider

Question Code
// I n c l u d e n e c e s s a r y Qt h e a d e r s
#include <QApplication >
#include <QHBoxLayout>
#include <Q S l i d e r >
#include <QSpinBox>

int main ( int argc , char ∗ argv [ ] )


{
// I n i t i a l i z e t h e Qt a p p l i c a t i o n
Q A p p l i c a t i o n app ( argc , argv ) ;

QWidget ∗window = new QWidget ; // Main a p p l i c a t i o n window


window−>setWindowTitle ( ” Enter Your Age” ) ; // S e t window t i t l e

QSpinBox ∗ spinBox = new QSpinBox ; // Spin box f o r numeric i n p u t


Q S l i d e r ∗ s l i d e r = new Q S l i d e r ( Qt : : H o r i z o n t a l ) ; // H o r i z o n t a l s l i d e r
main.cpp spinBox−>setRange ( 0 , 1 3 0 ) ; // S e t range f o r s p i n box
s l i d e r −>setRange ( 0 , 1 3 0 ) ; // S e t range f o r s l i d e r
#include <QApplication >
#include <QLineEdit> // Connect s p i n box v a l u e change t o s l i d e r v a l u e s e t
#include <QLCDNumber> QObject : : c o n n e c t ( spinBox , SIGNAL( valueChanged ( int ) ) ,
#include <QPushButton> s l i d e r , SLOT( s e t V a l u e ( int ) ) ) ;
#include <QMainWindow> // Connect s l i d e r v a l u e change t o s p i n box v a l u e s e t
#include <QVBoxLayout> QObject : : c o n n e c t ( s l i d e r , SIGNAL( valueChanged ( int ) ) ,
spinBox , SLOT( s e t V a l u e ( int ) ) ) ;
c l a s s MainWindow : public QMainWindow { spinBox−>s e t V a l u e ( 3 5 ) ; // S e t i n i t i a l v a l u e f o r s p i n box
Q OBJECT
QHBoxLayout ∗ l a y o u t = new QHBoxLayout ; // H o r i z o n t a l l a y o u t
public : l a y o u t −>addWidget ( spinBox ) ; // Add s p i n box t o l a y o u t
MainWindow ( QWidget ∗ p a r e n t = n u l l p t r ) ; l a y o u t −>addWidget ( s l i d e r ) ; // Add s l i d e r t o l a y o u t
˜MainWindow ( ) ; window−>s e t L a y o u t ( l a y o u t ) ; // S e t l a y o u t f o r main window

private s l o t s : window−>show ( ) ; // Show main window


void updateCharacterCount ( ) ;
void c a p i t a l i z e W o r d ( ) ; // E x e c u t e t h e a p p l i c a t i o n
return app . e x e c ( ) ;
private : }
QLineEdit ∗ l i n e E d i t ;
QLCDNumber ∗ l c d D i s p l a y ;
QPushButton ∗ c l o s e B u t t o n ;
QPushButton ∗ c a p i t a l i z e B u t t o n ;
};

MainWindow : : MainWindow ( QWidget ∗ p a r e n t ) :


QMainWindow ( p a r e n t ) ,
l i n e E d i t (new QLineEdit ( t h i s ) ) ,
l c d D i s p l a y (new QLCDNumber( t h i s ) ) ,
c l o s e B u t t o n (new QPushButton ( ” C l o s e ” , t h i s ) ) ,
c a p i t a l i z e B u t t o n (new QPushButton ( ” C a p i t a l i z e ” , t h i s ) )

1 1

{ Button Image
QWidget ∗ c e n t r a l W i d g e t = new QWidget ( t h i s ) ;
QVBoxLayout ∗ l a y o u t = new QVBoxLayout ( c e n t r a l W i d g e t ) ;

l a y o u t −>addWidget ( l i n e E d i t ) ;
l a y o u t −>addWidget ( l c d D i s p l a y ) ;
l a y o u t −>addWidget ( c l o s e B u t t o n ) ;
l a y o u t −>addWidget ( c a p i t a l i z e B u t t o n ) ;

setCentralWidget ( centralWidget ) ;

c o n n e c t ( l i n e E d i t , &QLineEdit : : textChanged , this , &MainWindow : : updateCharacterCount ) ;


c o n n e c t ( c l o s e B u t t o n , &QPushButton : : c l i c k e d , this , &MainWindow : : c l o s e ) ;
c o n n e c t ( c a p i t a l i z e B u t t o n , &QPushButton : : c l i c k e d , this , &MainWindow : : c a p i t a l i z e W o r d ) ; Note
updateCharacterCount ( ) ; This Qt application creates a simple interface to input an age using a spin box and a slider. The spin box allows numeric input,
} while the slider provides a horizontal graphical interface for the same purpose. Both the spin box and slider have a range from
0 to 130. The value changes in one widget are reflected in the other due to their interconnected signals and slots. The initial
MainWindow : : ˜ MainWindow ( ) {} value is set to 35.

void MainWindow : : updateCharacterCount ( ) {


int charCount = l i n e E d i t −>t e x t ( ) . l e n g t h ( ) ;
l c d D i s p l a y −>d i s p l a y ( charCount ) ;
}

void MainWindow : : c a p i t a l i z e W o r d ( ) {
QString t e x t = l i n e E d i t −>t e x t ( ) . toUpper ( ) ;
l i n e E d i t −>s e t T e x t ( t e x t ) ;
}

int main ( int argc , char ∗ argv [ ] ) {


Q A p p l i c a t i o n app ( argc , argv ) ;

MainWindow mainWindow ;
mainWindow . show ( ) ;

return app . e x e c ( ) ;
}

#include ”main . moc”

Button Image

2 2
// Connect b u t t o n s i g n a l s t o r e v e a l and f l a g f u n c t i o n s Note
c o n n e c t ( b u t t o n s [ i n d e x ] , &CustomButton : : l e f t C l i c k e d , this , [ this , i n d e x ] ( ) {
r e v e a l C e l l ( index ) ; This Qt application creates a main window with a line edit, an LCD display, and two buttons. The line edit allows the user to
}); input text, and the LCD display shows the character count of the input. The ”Close” button closes the application, while the
”Capitalize” button converts the input text to uppercase. The application uses signals and slots to update the character count
c o n n e c t ( b u t t o n s [ i n d e x ] , &CustomButton : : r i g h t C l i c k e d , this , [ this , i n d e x ] ( ) { and capitalize the text based on user interactions.
attachFlag ( index ) ;
});
}
}

c o n n e c t ( r e s t a r t B u t t o n , &QPushButton : : c l i c k e d , this , &MinesweeperWindow : : resetGame ) ;


c o n n e c t ( hintButton , &QPushButton : : c l i c k e d , this , &MinesweeperWindow : : g i v e H i n t ) ;

d i s t r i b u t e M i n e s ( ) ; // Randomly d i s t r i b u t e mines
c a l c u l a t e A d j a c e n t M i n e s ( ) ; // C a l c u l a t e a d j a c e n t mines f o r each c e l l
setWindowTitle ( ” Minesweeper ” ) ;
r e s i z e (400 , 450);
}

// P r o v i d e h i n t s t o t h e p l a y e r
void MinesweeperWindow : : g i v e H i n t ( ) {
i f ( gameOver ) {
return ;
}

// Find c e l l s t h a t can be s a f e l y r e v e a l e d or marked as mines


findSafeCells ();

// I f a l l mines a r e known , assume a l l remain ing c e l l s a r e s a f e


i f ( knownMines . s i z e ( ) == t o t a l M i n e s ) {
f or ( int row = 0 ; row < rows ; ++row ) {
f or ( int c o l = 0 ; c o l < c o l s ; ++c o l ) {
int i n d e x = row ∗ c o l s + c o l ;
Cell ∗ c u r r e n t C e l l = c e l l s [ index ] ;
i f ( ! c u r r e n t C e l l −>r e v e a l e d && ! knownMines . c o n t a i n s ( i n d e x ) ) {
i f ( ! s a f e C e l l s . contains ( index ) ) {
s a f e C e l l s . append ( i n d e x ) ; // Assume a l l rema ining c e l l s a r e s a f e i f mines
}
}
}
}
}

// R e v e a l a h i n t from t h e s a f e C e l l s l i s t
i f ( ! s a f e C e l l s . isEmpty ( ) ) {
int h i n t I n d e x = s a f e C e l l s . a t ( 0 ) ;
i f ( c e l l s [ h i n t I n d e x ]−> h i n t ) {
r e v e a l C e l l ( h i n t I n d e x ) ; // D i r e c t l y r e v e a l i f a l r e a d y h i n t e d ( second c l i c k )
return ;
}

c e l l s [ h i n t I n d e x ]−> h i n t = true ;
c e l l s [ h i n t I n d e x ]−> f l a g = f a l s e ;
c e l l s [ h i n t I n d e x ]−>u p d a t e I c o n ( ) ;
b u t t o n s [ h i n t I n d e x ]−> s e t I c o n ( c e l l s [ h i n t I n d e x ]−> i c o n ) ;
} else {
return ;
}
}

2 3

// Find s a f e c e l l s t h a t can be r e v e a l e d w i t h o u t r i s k
void MinesweeperWindow : : f i n d S a f e C e l l s ( ) {
bool change = f a l s e ;

// I d e n t i f y c e l l s t h a t can be s a f e l y marked as mines


Minesweeper Game Code
f or ( int row = 0 ; row < rows ; ++row ) {
f or ( int c o l = 0 ; c o l < c o l s ; ++c o l ) {
int i n d e x = row ∗ c o l s + c o l ;
Cell ∗ c u r r e n t C e l l = c e l l s [ index ] ;
i f ( c u r r e n t C e l l −>r e v e a l e d && c u r r e n t C e l l −>a d j a c e n t M i n e s > 0 ) {
int unrevealedCount = 0 ;
main.cpp
QVector<int> a d j a c e n t I n d i c e s ;
// I n c l u d e n e c e s s a r y Qt h e a d e r s and p r o j e c t −s p e c i f i c h e a d e r s
// Check a l l a d j a c e n t c e l l s #include ”MainWindow . h”
f or ( int i = −1; i <= 1 ; ++i ) { #include <QMessageBox>
f or ( int j = −1; j <= 1 ; ++j ) { #include <QRandomGenerator>
int neighborRow = row + i ; #include <QDebug>
int n e i g h b o r C o l = c o l + j ;
i f ( neighborRow >= 0 && neighborRow < rows && n e i g h b o r C o l >= 0 && n e i g h b o r // C o n s t r u c t o r f o r t h e MinesweeperWindow
int n e i g h b o r I n d e x = neighborRow ∗ c o l s + n e i g h b o r C o l ; MinesweeperWindow : : MinesweeperWindow ( QWidget ∗ p a r e n t ) : QMainWindow ( p a r e n t ) , t o t a l M i n e s ( 2 0 ) , rows
Cell ∗ neighbor = c e l l s [ neighborIndex ] ; auto ∗ w i d g e t = new QWidget ( t h i s ) ;
i f ( ! n e i g h b o r −>r e v e a l e d && ! s a f e C e l l s . c o n t a i n s ( n e i g h b o r I n d e x ) ) { setCentralWidget ( widget ) ;
unrevealedCount++;
a d j a c e n t I n d i c e s . append ( n e i g h b o r I n d e x ) ; auto ∗ l a y o u t = new QVBoxLayout ( w i d g e t ) ;
} s c o r e L a b e l = new QLabel ( ” S c o r e : 0” , t h i s ) ;
} auto ∗ r e s t a r t B u t t o n = new QPushButton ( ” R e s t a r t ” , t h i s ) ;
} auto ∗ h i n t B u t t o n = new QPushButton ( ” Hint ” , t h i s ) ;
}
// Add s c o r e l a b e l , r e s t a r t , and h i n t b u t t o n s t o t h e l a y o u t
// I f a l l u n r e v e a l e d c e l l s around a r e v e a l e d c e l l a r e mines , mark them as known mi auto ∗ buttonLayout = new QHBoxLayout ( ) ;
i f ( unrevealedCount == c u r r e n t C e l l −>a d j a c e n t M i n e s ) { buttonLayout−>addWidget ( s c o r e L a b e l ) ;
f or ( int a d j I n d e x : a d j a c e n t I n d i c e s ) { buttonLayout−>addWidget ( r e s t a r t B u t t o n ) ;
i f ( ! knownMines . c o n t a i n s ( a d j I n d e x ) ) { buttonLayout−>addWidget ( h i n t B u t t o n ) ;
knownMines . append ( a d j I n d e x ) ;
change = true ; l a y o u t −>addLayout ( buttonLayout ) ;
}
} // S e t up t h e g r i d l a y o u t f o r t h e game board
} auto ∗ g r i d L a y o u t = new QGridLayout ( ) ;
} gridLayout −>s e t S p a c i n g ( 0 ) ;
} gridLayout −>s e t C o n t e n t s M a r g i n s ( c o l s , rows , c o l s , rows ) ;
} l a y o u t −>addLayout ( g r i d L a y o u t ) ;
l a y o u t −>s e t A l i g n m e n t ( gridLayout , Qt : : A l i g n C e n t e r ) ;
// I d e n t i f y s a f e c e l l s t h a t can be r e v e a l e d
f or ( int row = 0 ; row < rows ; ++row ) { widget−>s e t L a y o u t ( l a y o u t ) ;
f or ( int c o l = 0 ; c o l < c o l s ; ++c o l ) {
int i n d e x = row ∗ c o l s + c o l ; // I n i t i a l i z e c e l l s and b u t t o n s
Cell ∗ c u r r e n t C e l l = c e l l s [ index ] ; c e l l s . r e s i z e ( rows ∗ c o l s ) ;
i f ( c u r r e n t C e l l −>r e v e a l e d && c u r r e n t C e l l −>a d j a c e n t M i n e s > 0 ) { b u t t o n s . r e s i z e ( rows ∗ c o l s ) ;
int n e i g h b o r M i n e s = 0 ;
QVector<int> a d j a c e n t I n d i c e s ; // Cr ea t e and c o n f i g u r e each b u t t o n and c e l l
f or ( int row = 0 ; row < rows ; ++row ) {
// Check a l l a d j a c e n t c e l l s f or ( int c o l = 0 ; c o l < c o l s ; ++c o l ) {
f or ( int i = −1; i <= 1 ; ++i ) { int i n d e x = row ∗ c o l s + c o l ;
f or ( int j = −1; j <= 1 ; ++j ) { c e l l s [ i n d e x ] = new C e l l ( ) ;
int neighborRow = row + i ; b u t t o n s [ i n d e x ] = new CustomButton ( ) ;
int n e i g h b o r C o l = c o l + j ; b u t t o n s [ i n d e x ]−> s e t F i x e d S i z e ( 3 0 , 3 0 ) ;
i f ( neighborRow >= 0 && neighborRow < rows && n e i g h b o r C o l >= 0 && n e i g h b o r b u t t o n s [ i n d e x ]−> s e t I c o n ( c e l l s [ i n d e x ]−> i c o n ) ;
int n e i g h b o r I n d e x = neighborRow ∗ c o l s + n e i g h b o r C o l ; b u t t o n s [ i n d e x ]−> s e t I c o n S i z e ( QSize ( 3 0 , 3 0 ) ) ;
Cell ∗ neighbor = c e l l s [ neighborIndex ] ; b u t t o n s [ i n d e x ]−> s e t F l a t ( true ) ;
i f ( ! n e i g h b o r −>r e v e a l e d ) { b u t t o n s [ i n d e x ]−> s e t S t y l e S h e e t ( ” b o r d e r : none ; ” ) ;
i f ( knownMines . c o n t a i n s ( n e i g h b o r I n d e x ) ) { gridLayout −>addWidget ( b u t t o n s [ i n d e x ] , row , c o l ) ;

3 1
s c o r e ++; n e i g h b o r M i n e s++;
updateScore ( ) ; }
checkWinCondition ( ) ; else {
a d j a c e n t I n d i c e s . append ( n e i g h b o r I n d e x ) ;
// R e c u r s i v e l y r e v e a l a d j a c e n t c e l l s i f no a d j a c e n t mines }
i f ( c e l l s [ i n d e x ]−> a d j a c e n t M i n e s == 0 ) { }
int row = i n d e x / c o l s ; }
int c o l = i n d e x % c o l s ; }
f or ( int i = −1; i <= 1 ; ++i ) { }
f or ( int j = −1; j <= 1 ; ++j ) {
int neighborRow = row + i ; // I f t h e number o f known mines around a r e v e a l e d c e l l matches i t s a d j a c e n t mines
int n e i g h b o r C o l = c o l + j ; i f ( n e i g h b o r M i n e s == c u r r e n t C e l l −>a d j a c e n t M i n e s ) {
i f ( neighborRow >= 0 && neighborRow < rows && n e i g h b o r C o l >= 0 && n e i g h b o r f or ( int a d j I n d e x : a d j a c e n t I n d i c e s ) {
int n e i g h b o r I n d e x = neighborRow ∗ c o l s + n e i g h b o r C o l ; i f ( ! s a f e C e l l s . contains ( adjIndex )){
i f ( ! c e l l s [ n e i g h b o r I n d e x ]−> r e v e a l e d ) { s a f e C e l l s . append ( a d j I n d e x ) ;
r e v e a l C e l l ( neighborIndex ) ; change = true ;
} }
} }
} }
} }
} }
} }
}
} // Find new s a f e c e l l s r e c u r s i v e l y
i f ( change ) {
// A t t a c h or d e t a c h a f l a g on a c e l l findSafeCells ();
void MinesweeperWindow : : a t t a c h F l a g ( int i n d e x ) { }
i f ( gameOver ) { }
return ;
} // R e v e a l a l l mines when t h e game i s o v e r
void MinesweeperWindow : : r e v e a l A l l M i n e s ( ) {
i f ( ! c e l l s [ i n d e x ]−> f l a g ) { f or ( int i = 0 ; i < mines . s i z e ( ) ; ++i ) {
c e l l s [ i n d e x ]−> f l a g = true ; mines [ i ]−> r e v e a l e d = true ;
c e l l s [ i n d e x ]−>u p d a t e I c o n ( ) ; mines [ i ]−>u p d a t e I c o n ( ) ;
b u t t o n s [ i n d e x ]−> s e t I c o n ( c e l l s [ i n d e x ]−> i c o n ) ; b u t t o n s [ m i n e s I n d e x e s . a t ( i )]−> s e t I c o n ( mines [ i ]−> i c o n ) ;
} else { }
c e l l s [ i n d e x ]−> f l a g = f a l s e ; }
c e l l s [ i n d e x ]−>u p d a t e I c o n ( ) ;
b u t t o n s [ i n d e x ]−> s e t I c o n ( c e l l s [ i n d e x ]−> i c o n ) ; // R e s e t t h e game t o i t s i n i t i a l s t a t e
} void MinesweeperWindow : : resetGame ( ) {
} gameOver = f a l s e ;

// Check i f t h e p l a y e r has won t h e game f or ( C e l l ∗ c e l l : c e l l s ) {


void MinesweeperWindow : : checkWinCondition ( ) { c e l l −>r e s e t ( ) ;
i f ( ! ( rows ∗ c o l s − t o t a l M i n e s == s c o r e ) ) { }
return ; safeCells . clear ();
} knownMines . c l e a r ( ) ;
QMessageBox : : i n f o r m a t i o n ( this , ” C o n g r a t u l a t i o n s ” , ”You win ! ” ) ; minesIndexes . c l e a r ( ) ;
gameOver = true ; mines . c l e a r ( ) ;
}
distributeMines ( ) ;
// Update t h e s c o r e d i s p l a y calculateAdjacentMines ( ) ;
void MinesweeperWindow : : u p d a t e S c o r e ( ) { score = 0;
s c o r e L a b e l −>s e t T e x t ( QString ( ” S c o r e : %1” ) . a r g ( s c o r e ) ) ; updateScore ( ) ;
} f or ( int i = 0 ; i < c e l l s . s i z e ( ) ; ++i ) {
b u t t o n s [ i ]−> s e t I c o n ( c e l l s [ i ]−> i c o n ) ;
}
Note }

This Qt application is a Minesweeper game. The game board is composed of a grid of cells, some of which contain hidden mines. // Randomly d i s t r i b u t e mines t o t h e board
The player reveals cells by clicking on them, trying to avoid the mines. The game provides two buttons, ”Restart” to reset the void MinesweeperWindow : : d i s t r i b u t e M i n e s ( ) {

6 4

game and ”Hint” to provide a hint for a safe move. The game also displays the player’s score, which is the number of cells int mineCount = t o t a l M i n e s ;
successfully revealed. If the player reveals a mine, the game is over. If the player successfully reveals all non-mine cells, they while ( mineCount > 0 ) {
win. int i n d e x = QRandomGenerator : : g l o b a l ()−>bounded ( rows ∗ c o l s ) ;
i f ( ! c e l l s [ i n d e x ]−>mine ) {
c e l l s [ i n d e x ]−>mine = true ;
mines . append ( c e l l s [ i n d e x ] ) ;
m i n e s I n d e x e s . append ( i n d e x ) ;
mineCount−−;
}
}
}

// C a l c u l a t e t h e number o f a d j a c e n t mines f o r each c e l l


void MinesweeperWindow : : c a l c u l a t e A d j a c e n t M i n e s ( ) {
f or ( int row = 0 ; row < rows ; ++row ) {
f or ( int c o l = 0 ; c o l < c o l s ; ++c o l ) {
int i n d e x = row ∗ c o l s + c o l ;
i f ( ! c e l l s [ i n d e x ]−>mine ) {
int mineCount = 0 ;
f or ( int i = −1; i <= 1 ; ++i ) {
f or ( int j = −1; j <= 1 ; ++j ) {
int neighborRow = row + i ;
int n e i g h b o r C o l = c o l + j ;
i f ( neighborRow >= 0 && neighborRow < rows && n e i g h b o r C o l >= 0 && n e i g h b o
int n e i g h b o r I n d e x = neighborRow ∗ c o l s + n e i g h b o r C o l ;
i f ( c e l l s [ n e i g h b o r I n d e x ]−>mine ) {
mineCount++;
}
}
}
}
c e l l s [ i n d e x ]−> a d j a c e n t M i n e s = mineCount ;
c e l l s [ i n d e x ]−>u p d a t e I c o n ( ) ;
}
}
}
}

// R e v e a l a c e l l and u p d a t e t h e game s t a t e a c c o r d i n g l y
void MinesweeperWindow : : r e v e a l C e l l ( int i n d e x ) {
i f ( ! s a f e C e l l s . isEmpty ( ) ) {
i f ( s a f e C e l l s . contains ( index )){
s a f e C e l l s . removeOne ( i n d e x ) ;
}
}

i f ( gameOver | | c e l l s [ i n d e x ]−> r e v e a l e d ) {
return ;
}

i f ( ! c e l l s [ i n d e x ]−> r e v e a l e d ) {
c e l l s [ i n d e x ]−> r e v e a l e d = true ;
c e l l s [ i n d e x ]−>u p d a t e I c o n ( ) ;
b u t t o n s [ i n d e x ]−> s e t I c o n ( c e l l s [ i n d e x ]−> i c o n ) ;

i f ( c e l l s [ i n d e x ]−>mine ) {
revealAllMines ( ) ;
QMessageBox : : i n f o r m a t i o n ( this , ”Game Over ” , ”You l o s e ! ” ) ;
gameOver = true ;
return ;
} else {

7 5
Main Application File 2023 QT Question
Create a main.cpp file to start the application: Consider the FindDialog class that was developed in the classroom. Develop the same class this time by
1 # include < QApplication > making use of the Qt Designer.
2 # include " FindDialog . h "
3
4 int main ( int argc , char * argv []) {
5 QApplication app ( argc , argv ) ;
6 FindDialog f ;
7 f . show () ;
8 return app . exec () ;
9 }

FindDialog Header
Create a header file for the FindDialog class:
1 # include < QWidget >
2 # include " ui_FindDialog . h "
Figure 1: Find Dialog Example
3
4 class FindDialog : public QWidget {
5 Q_OBJECT
6 Answer
7 public :
8 FindDialog () ;
1 # include < QApplication >
9
2 # include " FindDialog . h "
10 signals :
3
11 void findNext ( const QString & str , Qt :: CaseSensitivity cs ) ;
4 int main ( int argc , char * argv []) {
12 void findPrevious ( const QString & str , Qt :: CaseSensitivity cs ) ;
5 QApplication app ( argc , argv ) ;
13
6 FindDialog f ;
14 private slots :
7 f . show () ;
15 void findClicked () ;
8 return app . exec () ;
16 void enableFindButton ( const QString & text ) ;
9 }
17
10
18 private :
11 # include < QWidget >
19 Ui :: Form ui ;
12 # include " ui_FindDialog . h "
20 };
13
14 class FindDialog : public QWidget {
15 Q_OBJECT
FindDialog Implementation 16

17 public :
Implement the methods in the FindDialog class:
18 FindDialog () ;
1 # include < QWidget > 19
2 # include " FindDialog . h " 20 signals :
3 21 void findNext ( const QString & str , Qt :: CaseSensitivity cs ) ;
4 FindDialog :: FindDialog () : QWidget () { 22 void findPrevious ( const QString & str , Qt :: CaseSensitivity cs ) ;
5 ui . setupUi ( this ) ; 23
6 connect ( ui . lineEdit , SIGNAL ( textChanged ( const QString &) ) , 24 private slots :
7 this , SLOT ( enableFindButton ( const QString &) ) ) ; 25 void findClicked () ;
8 connect ( ui . findButton , SIGNAL ( clicked () ) , 26 void enableFindButton ( const QString & text ) ;
9 this , SLOT ( findClicked () ) ) ; 27
10 connect ( ui . closeButton , SIGNAL ( clicked () ) , 28 private :
11 this , SLOT ( close () ) ) ; 29 Ui :: Form ui ;
12 } 30 };
13 31
14 void FindDialog :: findClicked () { 32 # include < QWidget >
15 QString text = ui . lineEdit - > text () ; 33 # include " FindDialog . h "
16 Qt :: CaseSensitivity cs = 34
17 ui . caseCheckBox - > isChecked () ? Qt :: CaseSensitive : Qt :: CaseInsensitive ; 35 FindDialog :: FindDialog () : QWidget () {
18 if ( ui . backwardCheckBox - > isChecked () ) { 36 ui . setupUi ( this ) ;
19 emit findPrevious ( text , cs ) ; 37 connect ( ui . lineEdit , SIGNAL ( textChanged ( const QString &) ) ,
20 } else { 38 this , SLOT ( enableFindButton ( const QString &) ) ) ;
21 emit findNext ( text , cs ) ; 39 connect ( ui . findButton , SIGNAL ( clicked () ) ,
22 } 40 this , SLOT ( findClicked () ) ) ;

3 1

23 } 41 connect ( ui . closeButton , SIGNAL ( clicked () ) ,


24 42 this , SLOT ( close () ) ) ;
25 void FindDialog :: enableFindButton ( const QString & text ) { 43 }
26 ui . findButton - > setEnabled (! text . isEmpty () ) ; 44

27 } 45 void FindDialog :: findClicked () {


46 QString text = ui . lineEdit - > text () ;
47 Qt :: CaseSensitivity cs =
48 ui . caseCheckBox - > isChecked () ? Qt :: CaseSensitive : Qt :: CaseInsensitive ;
4. Building and Running the Application
49 if ( ui . backwardCheckBox - > isChecked () ) {
50 emit findPrevious ( text , cs ) ;
Compile and run your application using your preferred build system (e.g., qmake or CMake).
51 } else {
52 emit findNext ( text , cs ) ;
Using qmake 53 }
54 }
Example .pro file: 55

1 QT += core gui 56 void FindDialog :: enableFindButton ( const QString & text ) {


2 57 ui . findButton - > setEnabled (! text . isEmpty () ) ;
3 greaterThan ( QT_MAJOR_VERSION , 4) : QT += widgets 58 }
4
5 TARGET = FindDialog
6 TEMPLATE = app
7
Integrating UI from Qt Designer with C++
8 SOURCES += main . cpp FindDialog . cpp
9 In this lecture, we will discuss how to integrate a user interface (UI) designed with Qt Designer into a
10 HEADERS += FindDialog . h C++ application. We’ll use the example of a ‘FindDialog‘ to demonstrate the process.
11
12 FORMS += FindDialog . ui
Step-by-Step Guide
Using CMake 1. Designing the UI with Qt Designer
Example CMakeLists.txt: First, create your UI using Qt Designer:
1 c m a k e _ m i n i m u m _ r e q u i r e d ( VERSION 3.5) 1. Open Qt Designer.
2
3 project ( FindDialog )
2. Create a new dialog with buttons at the bottom.
4

5 set ( CM AK E_ CX X_S TA ND AR D 11)


3. Add the necessary widgets:
6 set ( C M A K E _ I N C L U D E _ C U R R E N T _ D I R ON )
7 set ( CMAKE_AUTOMOC ON )
• QLabel for ”Find what:”
8 set ( CMAKE_AUTOUIC ON )
9 • QLineEdit for user input
10 find_package ( Qt5Widgets REQUIRED )
11
• QCheckBox for ”Match case” and ”Search backward”
12 add_executable ( FindDialog main . cpp FindDialog . cpp ) • QPushButton for ”Find” and ”Close”
13 t a r g e t _ l i n k _ l i b r a r i e s ( FindDialog Qt5 :: Widgets )
4. Set the object names for easy reference in your code:

Detailed Explanations • QLineEdit: lineEdit


QApplication • QCheckBox: caseCheckBox and backwardCheckBox
• QPushButton: findButton and closeButton
The QApplication class manages application-wide resources and is required in every Qt GUI application.
It initializes the application and starts the event loop. 5. Save the design as FindDialog.ui.

QWidget
2. Converting the .ui File to a C++ Header
The QWidget class is the base class for all UI objects in Qt. It provides the basic functionality for visual
Use the ‘uic‘ tool to convert the .ui file to a C++ header:
elements, including event handling, layout, and painting.
1 uic -o ui_FindDialog . h FindDialog . ui

Ui::Form
The Ui::Form object is generated from the .ui file. It contains all the widgets and their properties as 3. Integrating the UI in C++
defined in Qt Designer. The setupUi method initializes the UI elements and sets up the connections. Create the C++ classes and methods to integrate the generated header.
Grid Layout Signals and Slots
A grid layout arranges widgets in a grid of rows and columns. Qt uses signals and slots to manage communication between objects. A signal is emitted when a particular
1 QGridLayout * gridLayout = new QGridLayout ; event occurs, and a slot is a function that is called in response to a particular signal. This mechanism is
2 gridLayout - > addWidget ( new QLabel ( " Label 1 " ) , 0 , 0) ; central to Qt’s event handling.
3 gridLayout - > addWidget ( new QLineEdit , 0 , 1) ;
4 gridLayout - > addWidget ( new QLabel ( " Label 2 " ) , 1 , 0) ;
5 gridLayout - > addWidget ( new QLineEdit , 1 , 1) ;
Connecting Signals and Slots
6
The connect function connects a signal to a slot:
7 QWidget * window = new QWidget ;
8 window - > setLayout ( gridLayout ) ; 1 connect ( ui . lineEdit , SIGNAL ( textChanged ( const QString &) ) ,
9 window - > show () ; 2 this , SLOT ( enableFindButton ( const QString &) ) ) ;
3 connect ( ui . findButton , SIGNAL ( clicked () ) ,
4 this , SLOT ( findClicked () ) ) ;
Form Layout 5 connect ( ui . closeButton , SIGNAL ( clicked () ) ,
6 this , SLOT ( close () ) ) ;
A form layout is typically used to create forms with labels and corresponding input fields.
1 QFormLayout * formLayout = new QFormLayout ;
2 formLayout - > addRow ( new QLabel ( " Name : " ) , new QLineEdit ) ;
Enabling the Find Button
3 formLayout - > addRow ( new QLabel ( " Age : " ) , new QSpinBox ) ; The enableFindButton slot enables or disables the Find button based on whether the line edit is empty
4
5 QWidget * window = new QWidget ; or not:
6 window - > setLayout ( formLayout ) ; 1 void FindDialog :: enableFindButton ( const QString & text ) {
7 window - > show () ; 2 ui . findButton - > setEnabled (! text . isEmpty () ) ;
3 }

Styling Widgets with Style Sheets


Handling Find Button Clicks
Qt allows you to style widgets using a powerful mechanism known as Qt Style Sheets (similar to CSS).
The findClicked slot emits either the findNext or findPrevious signal based on the state of the check-
boxes:
Basic Syntax
1 void FindDialog :: findClicked () {
The basic syntax for a Qt Style Sheet is similar to CSS. You can specify properties and values to style 2 QString text = ui . lineEdit - > text () ;
widgets. 3 Qt :: CaseSensitivity cs =
4 ui . caseCheckBox - > isChecked () ? Qt :: CaseSensitive : Qt :: CaseInsensitive ;
1 QPushButton * button = new QPushButton ( " Styled Button " ) ; 5 if ( ui . backwardCheckBox - > isChecked () ) {
2 button - > setStyleSheet ( " background - color : blue ; color : white ; font - size : 16 px ; " ) ; 6 emit findPrevious ( text , cs ) ;
7 } else {
8 emit findNext ( text , cs ) ;
Styling Multiple Widgets 9 }
10 }
You can apply styles to multiple widgets by specifying their class names or object names.
1 // Apply to all QPushButton instances
This guide provides a detailed walkthrough of integrating a Qt Designer UI into a C++ application,
2 qApp - > setStyleSheet ( " QPushButton { background - color : blue ; color : white ; } " ) ; demonstrating the process with a ‘FindDialog‘ example. Follow these steps to effectively use Qt Designer
3 with your C++ projects.
4 // Apply to a specific instance
5 button - > setObjectName ( " myButton " ) ;
6 button - > setStyleSheet ( " # myButton { background - color : red ; color : white ; } " ) ;

Using Pseudo-States
Qt Style Sheets support pseudo-states, which allow you to change the appearance of widgets based on
their state (e.g., hover, pressed).
1 QPushButton * button = new QPushButton ( " Hover Me " ) ;
2 button - > setStyleSheet ( " QPushButton { background - color : blue ; color : white ; }
QPushButton : hover { background - color : green ; } " ) ;

2 5

Advanced Styling Techniques Aligning and Styling Items in Qt


Using Gradient Backgrounds In this lecture, we will discuss how to align and style items in a Qt application. We will cover the following
You can create complex backgrounds using gradients. topics:
1 QPushButton * button = new QPushButton ( " Gradient Button " ) ; • Aligning Widgets
2 button - > setStyleSheet ( " QPushButton { background : qlineargradient ( spread : pad , x1 :0 , y1
:0 , x2 :1 , y2 :1 , stop :0 red , stop :1 yellow ) ; } " ) ; • Using Layouts

• Styling Widgets with Style Sheets


Setting Margins and Padding
You can set margins and padding to control the spacing around and within widgets. Aligning Widgets
1 QPushButton * button = new QPushButton ( " Padded Button " ) ;
2 button - > setStyleSheet ( " QPushButton { padding : 10 px ; margin : 5 px ; } " ) ; Qt provides several ways to align widgets within their parent containers.

Using Alignment Flags


Using Custom Fonts
You can use alignment flags to specify the alignment of a widget within its layout or parent container. The
You can use custom fonts to change the appearance of text in widgets. alignment flags can be combined using the bitwise OR operator (‘—‘). Here are some common alignment
1 QPushButton * button = new QPushButton ( " Custom Font Button " ) ; flags:
2 button - > setStyleSheet ( " QPushButton { font - family : ’ Courier New ’; font - size : 14 px ; } " )
; • Qt::AlignLeft
This lecture provides an overview of how to align and style items in Qt. By using alignment flags, • Qt::AlignRight
layouts, and style sheets, you can create visually appealing and well-organized Qt applications. Experiment
with these techniques to enhance the appearance and functionality of your UI. • Qt::AlignHCenter

• Qt::AlignTop

• Qt::AlignBottom

• Qt::AlignVCenter

1 QLabel * label = new QLabel ( " Aligned Text " ) ;


2 label - > setAlignment ( Qt :: AlignCenter ) ;

Using Layouts
Layouts are used to manage the size and position of widgets in a container. Qt provides several types of
layouts, including horizontal, vertical, grid, and form layouts.

Horizontal and Vertical Layouts


Horizontal and vertical layouts arrange widgets in a single row or column.
1 QHBoxLayout * hLayout = new QHBoxLayout ;
2 hLayout - > addWidget ( new QPushButton ( " Button 1 " ) ) ;
3 hLayout - > addWidget ( new QPushButton ( " Button 2 " ) ) ;
4
5 QVBoxLayout * vLayout = new QVBoxLayout ;
6 vLayout - > addWidget ( new QPushButton ( " Button 1 " ) ) ;
7 vLayout - > addWidget ( new QPushButton ( " Button 2 " ) ) ;
8
9 QWidget * window = new QWidget ;
10 window - > setLayout ( hLayout ) ; // or window - > setLayout ( vLayout ) ;
11 window - > show () ;

You might also like