QT Cheat
QT Cheat
QT Programming
Search
qt
Read:
C++
GUI
Programming
with
Qt-‐4
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);
}
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.
#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 !
1. https://en.wikipedia.org/wiki/Qt_(software)
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.
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.
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:
1. https://doc.qt.io/qt-5/qapplication.html 1. https://doc.qt.io/qt-5/qapplication.html
1. https://doc.qt.io/qt-5/signalsandslots.html
1. https://doc.qt.io/qt-5/qtimer.html#details
1. We check widgets in
GridLayout.
2. Then, typecast to
ColorButton as we know all
widgets are ColorButtons.
● 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>
// 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
}
// 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 ) ;
// 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 ) ;
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>
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 ) ;
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 ) ;
}
MainWindow mainWindow ;
mainWindow . show ( ) ;
return app . e x e c ( ) ;
}
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 ) ;
});
}
}
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 ;
}
// 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 ;
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 ;
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−−;
}
}
}
// 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
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 }
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
• Qt::AlignTop
• Qt::AlignBottom
• Qt::AlignVCenter
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.