You are on page 1of 242

Qt

/

/


( )
( )

( ) ( )
()


( ) Cross-Platform


( ) windows ( ) Mac OSX ( ) Linux
( ) Symbian ()Windows Mobile
( .) Embedded Linux

++

++

( ) Compiling

.




.
:





.











.




.


.
:
C++ Object Oriented Programming
( Qt Nokia SDK Software )
................................................................................


2
8
9
12
14
17
20
23
24
27
28
30
32
34
36
39
41
43
44
50
52
53
56
58
60
62
65

..............................................................................................................
.............................................................................................
............... ) QtCore Module (
............................................................................................ QDebug

........................................................................................ QBitArray

..................................................................................... QByteArray
............................................................................................. QString
...................................................... ) Container Classes (

..................................................................................... QList

................................................................................ QVector

................................................................................ QQueue

.................................................................................. QStack

.......................................................................... QStringList

...................................................................................... QSet

.................................................................................... QMap

.......................................................................... QMultiMap

.............................................................. ) Iterator Classes (

.......................................................................... Java Style Iterator

.......................................................................... STL Style Iterator

........................................................................... foreach Keyword

................................................................................................. QDir

.......................................................................................... QFileInfo

................................................................................................. QFile

.................................................................................... QTextStream

................................................................................... QDataStream

.......................................................................................... QVariant

........................................................................................... QObject


( ........... ) QtGui Module
........................................................................................... QWidget

........................................................................................... QPainter

............................................................................................ QDialog

............................................................................... QMainWindow

( ..................................................... ) Layout Managment

( ...................................................... ) Drag and Drop

- ( .................................................... ) Model / View

..........................................................................

.................................................................

..........................................................

( ....................................... ) Graphics View Framework

.................................................................. QGraphicsScene

................................................................... QGraphicsView

.................................................................... QGraphicsItem

( ............................................. ) Animation Gui

( ......................... ) QNetwork Module
................................................................................. QHostAddress

........................................................................................ QHostInfo

...................................................................................... QTcpServer

...................................................................................... QTcpSocket

.................................................................................... QUdpSocket

(................. ) QtSql Module
( ............................ ) Multithreaded Programming
................................................................................

83
86
103
104
108
113
121
131
138
141
144
149
152
153
154
161
169
172
173
177
187
195
205
217

( ) 1 ( .................................... ) Memory Managment


( ) 2 ......................................................... C++
( ) 3 ....................................................................
( ) 4 ................................ QtCreator
( ) 5 ................................................... QObject
................................................................................

228
229
231
235
236


Examples Name

QDebug Example
QBitArray Example
QByteArray Example
QString Example
QList Example
QVector Example
QQueue Example
QStack Example
QStringList Example
QSet Example
QMap Example
QMultiMap Example
Java_Iterator Example
STL_Iterator Example
foreach Example
QFileInfo Example
QFile Example
QTextStream Example
QDataStream Example
QVariant Example
QObject Example
QWidget Example
Car GUI Example
QPainter Example
QDialog Example
QMainWindow Example

Page EX:No Examples Name


13
15
18
21
25
27
29
31
33
35
37
40
46
48
50
54
57
58
60
62
73
87
94
101
105
109

EX_1
EX_2
EX_3
EX_4
EX_5
EX_6
EX_7
EX_8
EX_9
EX_10
EX_11
EX_12
EX_13
EX_14
EX_15
EX_16
EX_17
EX_18
EX_19
EX_20
EX_21
EX_22
EX_23
EX_24
EX_25
EX_26

Layout Example
Drag_Drop Example
ListView Example
TableView Example
TreeView Example
Graphics Example
Animation GUI Example
QHostInfo Example
QHostAddress Example
QTcpServer Example
QTcpSocket Example
QUdpSender Example
QUdpReceiver Example
Databse Example
QThread Example

Page EX:No
116
125
138
141
144
155
164
174
174
179
189
196
200
211
222

EX_27
EX_28
EX_29
EX_30
EX_31
EX_32
EX_33
EX_34
EX_34
EX_35
EX_36
EX_37
EX_38
EX_39
EX_40

( ) Modules

( ) Classes
.
( ) Modules :

Module

QtCore
QtGui
QtMultimedia
QtNetwork
QtOpenGL
QtOpenVG
QtScript
QtSql
QtSvg
QtWebKit
QtXml
Phonon

.
. GUI
.MultiMedia
.
.OpenGL
.OpenVG
.Qt Scripts
.DataBases
.SVG
.Web content
.XML
.

QAxContainer
QAxServer

.Windows ActiveX Control


Server .Windows ActiveX

Windows OS
UNIX OS
QtDBus

.Inter-Process Communication


:
.QtNetwork Module , QtSql Module , QtGui Module :

QtCore Module

QtCore Module

>#include <QtCore

QT += core
. project.pro

10

QtCore Module

( ) Qt Modules
.
:
:


.

:


.

:QObject
.

................................................................................
.
:
:

( : ) 3 .223 ( : ) 4 QtCreator .227................................................................................

QtCore Module

11

QDebug Class

:


:
( .) Console

( : ) Declaration
:

;) qDebug( Value To Print


;qDebug() << value = << 10

:
qDebug ( >> )

qDebug .

qDebug
.
................................................................................

12

QtCore Module

QDebug Example

#include <QtCore>

EX

Am
NO ple
1

int main()
{
qDebug( Hi Qt Developers ! ) ;
qDebug() << Hi Qt Developers !! again ;
qDebug() << 10+20 = << 10+20 ;
}

:
) Console (

qDebug( Hi Qt Developers ! );

) Console ( Hi Qt Developers !

qDebug() << Hi Qt Developers !! again;

. Hi Qt Developers !! again

qDebug() << 10+20 = << 10+20;

................................................................................

13

QtCore Module

. 30 = 10+20

QBitArray Class

:


:
( ) Bits

.True or False 01
( : ) Declaration
:

;)QBitArray x(8
x 8 ( ) Bits
0 False 1
True :
;)QBitArray x(8,true
:

x .true or false
)at(int x
true .
)(isNull
true .0
)(isEmpty
x .true
)setBit(int x
) setBit(int x, bool t x t t .true or false

isNull , isEmpty :

;QBitArray x
x.isNull() ---> will return true.
x.isEmpty() ---> will return true.

;)QBitArray x(0
x.isNull() ---> will return false.
x.isEmpty() ---> will return true.
14

QtCore Module

#include <QtCore>
int main()
{
QBitArray x( 8 );
QBitArray y( 8 , true );
QBitArray r( 8 );
x.setBit( 0 );
x.setBit( 1 );
x.setBit( 2 );
x.setBit( 3 );
x.setBit( 4 );

QBitArray Example
EX

Am
NO ple
2

y.setBit( 0 , false );
y.setBit( 1 , false );
y.setBit( 2 , false );
r = x & y;
r = x | y;
r = x ^ y;
r = ~x;
r = y;

:
QBitArray x( 8);
QBitArray y( 8 , true );
QBitArray r( 8 );
x.setBit( 0 );
x.setBit( 1 );

15

0|0|0|0|0|0|0|0

1|1|1|1|1|1|1|1

0|0|0|0|0|0|0|0

1|0|0|0|0|0|0|0

True x 0

1|1|0|0|0|0|0|0

True x 1

QtCore Module

;) x.setBit( 2

2 x True

1|1|1|0|0|0|0|0

3 x True

1|1|1|1|0|0|0|0

4 x True

1|1|1|1|1|0|0|0

0 y False

0|1|1|1|1|1|1|1

1 y False

0|0|1|1|1|1|1|1

2 y False

0|0|0|1|1|1|1|1

= r
= r

1|1|1|1|1|1|1|1

= r

1|1|1|0|0|1|1|1

= r

0|0|0|0|0|1|1|1

= r

0|0|0|1|1|1|1|1

16

;) x.setBit( 4
;) y.setBit( 0 , false
;) y.setBit( 1 , false

x , y:
1|1|1|1|1|0|0|0 X


0|0|0|1|1|0|0|0

;) x.setBit( 3

QtCore Module

;) y.setBit( 2 , false

0|0|0|1|1|1|1|1

r = x & y; <-- AND Operator


r = x | y; <-- OR Operator
r = x ^ y; <-- XOR Operator
<-- NOT Operator

;r = ~x

<-- Equal Operator

;r = y

QByteArray Class

:


:
( ) Bytes

0 256 .
( : ) Declaration
:

;) QBitArray x( Test
x 4 . T,E,S,T
;) QBitArray x( 5 , T
x 5 . T,T,T,T,T
:

)at(int x
)left(int x
)right(int x
)mid(int P , int L
)(trimmed
)chop(int L
)truncate(int L

.x
x .
x .
L .P
.
L .
L .

................................................................................

QtCore Module

17

#include <QtCore>
int main()
{
QByteArray ar( Hello );
QByteArray br( 5 , Q );
qDebug() << ar.trimmed();
ar = ar.trimmed() + br;
qDebug() << ar[ 0 ];
qDebug() << ar.at( 1 );
qDebug() << ar.left( 2 );
qDebug() << ar.right( 7 );
qDebug() << ar.mid( 3 , 4 );
ar.chop( 7 );
ar.truncate( 2 );
}

QByteArray Example
EX

Am
NO ple
3

QByteArray ar( Hello );

H|e|l|l|o| | | | |

QByteArray br( 5 , Q );

Q|Q|Q|Q|Q

qDebug() << ar.trimmed();


ar = ar.trimmed() + br;
qDebug() << ar[ 0 ];

10 ar
5 br
Hello

H|e|l|l|o|Q |Q |Q |Q |Q

= ar

. 0 H

QtCore Module

18

;) qDebug() << ar.at( 1

e 1 .

;) qDebug() << ar.left( 2

He 2 .
loQQQQQ 7 .

;) qDebug() << ar.right( 7

;) qDebug() << ar.mid( 3 , 4


loQQ 4 3 .
= ar
H | e | l
H | e
= ar

7.
2 .

;) ar.chop( 7
;) ar.truncate( 2

................................................................................

QtCore Module

19

QString Class

:


:


( ) Strings
16 ( ) UniCode
.
( : ) Declaration


;) QString str( string


;QString str
;str = string

:


.
.
.

str .
)append(str
) insert(int p , str str .p
) remove(int P ,int L L .p
) replace(str1,str2 str2 .str1
True .str
)contains(str
True .str
)startsWith(str
True .str
)endsWith(str
) setNum(number number .

QString
.
20

QtCore Module

#include <QtCore>

QString Example
EX

int main()
{
QString str( Hello Qt );
str += Developer;
str.append( 2010 );
str.insert( 0 , Hello !! );
str.remove( 6 , 3 );
str.replace( 2010 , 2011 );
qDebug() << str.contains( Dev );
qDebug() << str.startsWith( Hello );
qDebug() << str.startsWith( Hi );
qDebug() << str.endsWith( 10 );
qDebug() << str.endsWith( 11 );
qDebug() << str.setNum( 2010.11 );
qDebug() << QString::number( 10 , 2 );
qDebug() << QString::number( 10 , 16 );
QString strarg( Hi %1 %2 );
qDebug() << strarg.arg( Qt , Developer );
}

QString str( Hello Qt );

.Hello Qt Developer str

str.append( 2010 );

str.remove( 6 , 3 );

21

.Hello Qt QString str

str += Developer;

str.insert( 0 , Hello !! );

Am
NO ple
4

.Hello Qt Developer 2010 str


.Hello !! Hello Qt Developer 2010 str
.Hello Hello Qt Developer 2010 str

QtCore Module

str.replace( 2010 , 2011 );


qDebug() << str.contains( Dev );
qDebug() << str.startsWith( Hello );
qDebug() << str.startsWith( Hi );
qDebug() << str.endsWith( 10 );
qDebug() << str.endsWith( 11 );
qDebug() << str.setNum( 2010.11 );

.Hello Hello Qt Developer 2011 str


.Dev str True
.Hello str True
.Hi str False
.10 str False
.11 str True
. 2010.11

qDebug() << QString::number( 10 , 2 );


.)Binary (2 10 1010
qDebug() << QString::number( 10 , 16 );
.)Hexadecimal ( 16 10 a
QString strarg( Hi %1 %2 );
qDebug() << strarg.arg( Qt , Developer );
Developer Qt %2 , %1 Hi Qt Developer
.Function Arguments
QtCore Module

22

(:)Container Classes



.
( )
( )Iterator Classes .
:

T
>QList<T
( )Pointers ( ) Data
.
( ) Data
>QVector<T
( ) Pointers
.
QList .FIFO
>QQueue<T
QVector .LIFO
>QStack<T

>QSet<T
.
( )Key (. )T
>QMap<Key,T
( )key,T
.
> QMultiMap<Key,T QMap ( )Key (.)T
> QHash<Key,T QMap QHash
.
> QMultiHash<Key,T QHash .

................................................................................

QtCore Module

23

QList Class

:


:
( ) Container Classes

( ).
( : ) Declaration
:

;QList<data type> name


;EX: QList<QString> strlist
( ) QString strlist
( ) . (>>).
;EX: strlist << name1 << name2 << name2

strlist .name1,nam2,nam3

val .
) append( val
) insert(int p , val val .p
) swap(int v1 ,int v2 v2 .v1
) removeAt( int p .p
.
)(pop_back
.
)(pop_front
) push_back( val val .
) push_front( val val .
) indexOf( val ( ) .val
.p
) value( int p
) move(int v1,int v2 v1 .v2
) prepend( val val .
.
)(size
. val
) count( val
) removeAll( val . val

24

QtCore Module

#include <QtCore>

QList Example
EX

Am
NO ple
5

int main()
{
QList<int> mylist;
mylist << 0 << 1 << 2 << 3 << 5 << 7 << 6;
mylist.append( 8 );
mylist.insert( 4 , 4 );
mylist.swap( 7 , 6 );
mylist.removeAt( 8 );
mylist.pop_back();
mylist.pop_front();
mylist.push_back( 7 );
mylist.push_front( 0 );
qDebug() << mylist.indexOf( 1 );
qDebug() << mylist.value( 3 );
mylist.move( 1, 5 );
mylist.prepend( 0 );
qDebug() << mylist.size();
qDebug() << mylist.count( 0 );
}

QList<int> mylist;
mylist << 0 << 1 << 2 << 3 << 5 << 7 << 6;
.)int( mylist
No 0 | 1 | 2 | 3 | 4 | 5 | 6
.
Value 0 | 1 | 2 | 3 | 5 | 7 | 6
mylist.append( 8 );
No 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 . 8
Value 0 | 1 | 2 | 3 | 5 | 7 | 6 | 8

mylist.insert( 4 , 4 );
No 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8
Value 0 | 1 | 2 | 3 | 4 | 5 | 7 | 6 | 8

.4 4

mylist.swap( 7 , 6 );
No 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8
Value 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8

25

QtCore Module

.6 7

.8

;) mylist.removeAt( 8
No 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7
Value 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7

No 0 | 1 | 2 | 3 | 4 | 5 | 6
Value 0 | 1 | 2 | 3 | 4 | 5 | 6

No 0 | 1 | 2 | 3 | 4 | 5
Value 1 | 2 | 3 | 4 | 5 | 6

7 .

;)(mylist.pop_back
;)(mylist.pop_front
;) mylist.push_back( 7

No 0 | 1 | 2 | 3 | 4 | 5 | 6
Value 1 | 2 | 3 | 4 | 5 | 6 | 7

;) qDebug() << mylist.indexOf( 1


0 1 .0
;) qDebug() << mylist.value( 3

4 .3
1 .5

0 .

;) mylist.move( 1 , 5
No 0 | 1 | 2 | 3 | 4 | 5 | 6
Value 1 | 3 | 4 | 5 | 6 | 2 | 7

;) mylist.prepend( 0
No 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7
Value 0 | 1 | 3 | 4 | 5 | 6 | 2 | 7

8 .
1 0 .

26

QtCore Module

;)(qDebug() << mylist.size


;) qDebug() << mylist.count( 0

QVector Class

:


:
QList

( . .) 25
( : ) Declaration
:

;QVector<data type> name
;EX: QVector<QString> strlist
strlist ( ) QString
( ) (>>).

;EX: strlist << name1 << name2 << name2


strlist .name1,nam2,nam3
:

val .
) append( val
) insert(int p , val val .p
) remove( int p .p
) remove(int p, int L L .p
.
)(pop_back
.
)(pop_front
) push_back( val val .
) push_front( val val .
( ) .val
) indexOf( val
.p
) value( int p
val .
) prepend( val
.
)(size
. val
) count( val

* .QList

EXAmple
NO 6

QtCore Module

27

QQueue Class

:
QList

:
QList ( ) FIFO

.
( : ) Declaration
.QList

;QQueue<data type> name
;EX: QQueue<int> myqueue
myqueue . int
:

)(dequeue
) enqueue( val
)(head

.
.QList::append
.0

4
3
2

FIFO System
First In First Out

1
0
0
28

OUT
QtCore Module

IN

#include <QtCore>

QQueue Example

int main()
{
QQueue<QString> myqueue;
myqueue << Ahmed ; //First In
myqueue << Osama ;
myqueue << sami; //Last In

EX

Am
NO ple
7

qDebug() << myqueue;


qDebug() << myqueue.dequeue();
qDebug() << myqueue;
qDebug() << myqueue.dequeue();
qDebug() << myqueue;
qDebug() << myqueue.head();
myqueue.enqueue(Mahmoud);
qDebug() << myqueue;

QQueue<QString> myqueue;
myqueue << Ahmed ;
myqueue << Osama ;
myqueue << sami;
.QString myqueue
.Ahmed , Osama , sami
qDebug() << myqueue.dequeue();
. Ahmed
.Osama , sami
qDebug() << myqueue.dequeue();
. Osama
.sami
myqueue.enqueue(Mahmoud);
. Mahmoud
.sami , Mahmoud

29

QtCore Module

QStack Class

:
QVector

:
QVector ()LIFO

.
( : ) Declaration
.QVector

;QStack<data type> name


;QStack<int> mystack
mystack . int
:

)(pop
) push( val
)(top

.
. val
.

4
LIFO System
Last In First Out

OUT

4
3
2
1
0

30

QtCore Module

IN

QStack Example

#include <QtCore>

EX

Am
NO ple
8

int main()
{
QStack<QString> mystack;
mystack << AHmed ; //First In
mystack << Osama ;
mystack << sami; //Last In

qDebug() << mystack;


qDebug() << mystack.pop();
qDebug() << mystack;
qDebug() << mystack.pop();
qDebug() << mystack;
qDebug() << mystack.top();
mystack.push(Mahmoud);
qDebug() << mystack;

QStack<QString> mystack;
mystack << AHmed ;
mystack << Osama ;
mystack << sami;
qDebug() << mystack.pop();
qDebug() << mystack.pop();
mystack.push(Mahmoud);

31

.QString mystack
.Ahmed , Osama , sami
. sami
.Ahmed , Osama
. Osama
. Ahmed

QtCore Module

. Mahmoud
.Ahmed , Mahmoud

QStringList Class

:
QList

:
QList

.
QList<QString> :
( : ) Declaration
;QStringList mylist
(>>).

;mylist << Osama << Mohamed << Samier
:



.
:

.
)(sort
) filter( QString str .str
) join( QString str .str

................................................................................

32

QtCore Module

#include <QtCore>

QStringList Example
EX

int main()
{
QStringList mylist;
mylist << Osama << Mohamed << Ali << Samier ;

Am
NO ple
9

mylist.sort();
qDebug() << mylist.filter(med);
QStringList mylist2;
QString str(Mahmoud,Ali,Said,Sami,Mohamed);
mylist2 = str.split( , );
}

str = mylist2.join( - );

QStringList mylist;
mylist << Osama << Mohamed << Ali << Samier ;
.QStringList ) QString( mylist
.Osama , Mohamed , Ali , Samier
mylist.sort();
.Ali,Mohamed,Osama,Samier :
QStringList mylist2;
QString str(Mahmoud,Ali,Said,Sami,Mohamed);
. )QString( mylist2
.QString str
mylist2 = str.split( , );
. ,
str = mylist2.join( - );

33

.-
. Mahmoud-Ali-Said-Sami-Mohamed: str

QtCore Module

QSet Class

:


:


.
( : ) Declaration
;QSet<data type> name
;EX : QSet<int> myset
(>>).

;myset << 1 << 2 << 3 << 4
:
.

.s
.s
.s

)intersect(QSet s
)subtract(QSet s
)unite(QSet s

.
9
4
3

34

3
6

1 2
5
2
7

1
2

QtCore Module

4
7 2

#include <QtCore>

QSet Example

int main()
{
QSet<int> myset;
myset << 1 << 2 << 3 << 2 << 5 << 1 << 3 << 1 << 2 << 3 << 5;

EX
Am
NO ple
10

QSet<int> myset2;
myset2 << 5 << 7 << 2 << 9 << 8;

qDebug() << myset.intersect( myset2 );


qDebug() << myset2.subtract( myset );
qDebug() << myset.unite( myset2 );

QSet<int> myset;
myset << 1 << 2 << 3 << 2 << 5 << 1 << 3 << 1 << 2 << 3 << 5;
1 myset
. myset
QSet<int> myset2;
myset2 << 5 << 7 << 2 << 9 << 8;
.myset = (1,2,3,5) and myset2 = (5,7,2,8,9)
qDebug() << myset.intersect( myset2 );
.myset2 myset myset
.myset = (2,5) and myset2 = (5,7,2,8,9)
qDebug() << myset2.subtract( myset );
.myset2 myset myset2
myset = (2,5) and myset2 = (7,8,9)
qDebug() << myset.unite( myset2 );
.myset2 myset myset2
myset = (2,5789) and myset2 = (7,8,9)

35

QtCore Module

QMap Class

:


:
()pairs

( ) ( )Key , Value

. QMultiMap
( : ) Declaration
;QMap<KEY data type ,VALUE data type> name
;EX : QMap<QString,int> mymap
mymap :
( ) ( ).

:

:

)key(value v
)keys(value v
)(keys
)value(key k
)(values
)take(key k
)(count

;)mymap.insert(good,1
;mymap[bad] = 0

.v
.v
.
.k
.
k .k
.

................................................................................

36

QtCore Module

#include <QtCore>
int main()
{
QMap <QString , int > mymap;

QMap Example
EX
Am
NO ple
11

mymap[hadi] = 2;
mymap[sami]
= 2;
mymap.insert( ali , 1 );
mymap.insert( hadi , 1 );
qDebug() << mymap.key( 1 );
qDebug() << mymap.keys( 1 );
qDebug() << mymap.keys();
qDebug() << mymap.value( sami );
qDebug() << mymap.values();
}

qDebug() << mymap.take( ali );

QMap <QString , int > mymap;


mymap[hadi] = 1;
mymap[sami] = 2;
mymap.insert( ali , 1 );
mymap.insert( hadi , 1 );
Key

ali
hadi
sami

Value
1
1
2

. mymap
.

) key (
) 1 ( ) 2 ( ) hadi (
.

37

QtCore Module

;) qDebug() << mymap.key( 1

ali .1
ali , hadi .1

;) qDebug() << mymap.keys( 1


;)(qDebug() << mymap.keys

.ali , hadi , sami

;) qDebug() << mymap.value( sami

2 .sami

;)(qDebug() << mymap.values

.112

;) qDebug() << mymap.take( ali


1 ali :
Value
1
2

Key

hadi
sami

................................................................................

38

QtCore Module

QMultiMap Class

:
QMap

:
QMap

.
( : ) Declaration
;QMultiMap<KEY data type ,VALUE data type> name
;EX : QMultiMap<QString,int> mymap
mymap :
( ) ( ).

:

;) mymap.insert( good , 1
;mymap[bad] = 0

. QMap

)values(key k
)count(key k

.k
.k

................................................................................

QtCore Module

39

QMultiMap Example

#include <QtCore>
int main()
{
QMultiMap <QString , int > myMmap,myMmap1,myMmap2;
myMmap1.insert( ali , 1 );
myMmap1.insert( sami , 1 );
myMmap1.insert( mohamed , 1 );
myMmap2.insert( sami , 2 );
myMmap2.insert( ali , 3 );
myMmap2.insert( sami , 1 );
myMmap2.insert( ali , 4 );
myMmap = myMmap1 + myMmap2;
}

EX
Am
NO ple
12

QMultiMap <QString , int > myMmap,myMmap1,myMmap2;


. mymap,mymap1,mymap2
myMmap1.insert(ali , 1 );
myMmap1.insert(sami , 1 );
myMmap1.insert(mohamed , 1 );
myMmap2.insert(sami
myMmap2.insert(ali
myMmap2.insert(sami
myMmap2.insert(ali

, 2 );
, 3 );
, 1 );
, 4 );

myMmap = myMmap1 + myMmap2;

Key
ali
mohamed
sami
Key
ali
ali
sami
sami

maymap1

maymap2

Value
1
1
1
Value
4
3
1
2

mymap

Key
Value
ali
4
ali
3
ali
1
mohamed
1
sami
1
sami
2
sami
1
QtCore Module

40

:)Iterator Classes(


.) STL - Style -Iterators ), ( Java-Style- Iterators ( :
:)Java Style Iterator(
.STL
:)Iterator Classes(
Containers
QList<T>, QQueue<T>
QLinkedList
QVector<T>, QStack<T>

Read-only iterator
QListIterator
QLinkedListIterator<T>
QVectorIterator<T>

Read-write iterator
QMutableListIterator
QMutableLinkedListIterator
QMutableVectorIterator<T>

QSet<T>
QMap<Key, T>, QMultiMap<Key, T>
QHash<Key, T>, QMultiHash<Key, T>

QSetIterator<T>
QMapIterator<Key, T>
QHashIterator<Key, T>

QMutableSetIterator<T>
QMutableMapIterator<Key, T>
QMutableHashIterator<Key, T>

:)STL Style Iterator(


2.0
.
:)Iterator Classes(
Containers
QList<T>, QQueue<T>
QLinkedList
QVector<T>, QStack<T>

Read-only iterator
QList<T>::const_iterator
QLinkedList<T>::constiterator
QVector<T>::const_iterator

Read-write iterator
QList<T>::iterator
QLinkedList<T>::iterator
QVector<T>::iterator

QSet<T>
QMap<Key, T>, QMultiMap<Key, T>
QHash<Key, T>, QMultiHash<Key, T>

QSet<T>::const_iterator
QMap<Key, T>::const_iterator
QHash<Key, T>::const_iterator

QSet<T>::iterator
QMap<Key, T>::iterator
QHash<Key, T>::iterator

QList
.
................................................................................
41

QtCore Module

QListIterator Class

:


:
.Java - Style - Iterator

( : ) Declaration
;)QListIterator<data type> name(QList
EX:
;QList<QString> mylist
;)QListIterator<QString> iter(mylist
mylist .QString
iter .mylist
:

.
.STL

( .) next

( )next (.)previous
42

QtCore Module

(.)previous
)( hasNext
)( hasPrevious
)( next
)( previous
)( peekNext
)( peekPrevious
)( toBack
)( toFront

true .
true .
.
.
.
.
.
.

................................................................................

QtCore Module

43

STL Style Iterator


( : ) Declaration

;Container class<data type>::iterator name


EX:
;QList<QString> mylist
;QList<QString>::iterator iter
mylist .QString
iter .mylist
:

.
.
)(end

(.)++
)(end

( )++ (.)--44

QtCore Module

)(end

( )-- ( () ) end
.

*iterator
)( end
)( begin
++ iterator
-- iterator
iterator += n
iterator -= n
iterator - j

.
().end
.
.
.
n .
n .
iterator .j

................................................................................

QtCore Module

45

QListIterator Example

#include <QtCore>
int main()
{
QList<QString> mylist;
mylist << Ali << Mohamed << Mohsen << Sami;
QListIterator<QString> itr(mylist);
while(itr.hasNext())
qDebug() << itr.next();
while(itr.hasPrevious())
qDebug() << itr.previous();
qDebug() << itr.peekNext();
itr.toBack();
qDebug() << itr.previous();
}

EX
Am
NO ple
13

QList<QString> mylist;
mylist << Ali << Mohamed << Mohsen << Sami;
. mylist
Ali

Mohamed

mylist

Mohsen

Sami

QListIterator<QString> itr(mylist);
. mylist itr
Ali

while(itr.hasNext())
qDebug() << itr.next();

Ali

Mohamed

mylist

Mohsen

Sami

.
Mohamed

mylist

Mohsen

Sami

QtCore Module

46

))(while(itr.hasPrevious
;)(qDebug() << itr.previous
.
Sami

Mohsen

mylist

Mohamed

Ali

;)(qDebug() << itr.peekNext


( )Ali .
Sami

Mohsen

mylist

Mohamed

Ali

;)(itr.toBack

.
Sami

Mohsen

mylist

Mohamed

Ali

;)(qDebug() << itr.previous


( )Sami .
Sami

Mohsen

mylist

Mohamed

Ali

................................................................................

QtCore Module

47

STL Iterator Example

#include <QtCore>
int main()
{
QList<QString> mylist;
mylist << Ali << Mohamed << Mohsen << Sami;

EX
Am
NO ple
14

QList<QString>::iterator itr;
for( itr = mylist.begin() ; itr != mylist.end() ; itr++)
qDebug() << *itr;
--itr;
qDebug() << *( itr );
qDebug() << *( --itr );
qDebug() << *( --itr );
qDebug() << *( ++itr );
*(itr) = Modified;

QList<QString> mylist;
mylist << Ali << Mohamed << Mohsen << Sami;
. mylist
Ali

Mohamed

mylist

Mohsen

Sami

end()

QList<QString>::iterator itr;
. 0 mylist itr
Ali

Mohamed

mylist

Mohsen

Sami

end()

for(itr = mylist.begin() ; itr != mylist.end() ; itr++)


qDebug() << *itr;
.) end )( (
Ali

Mohamed

mylist

Mohsen

Sami

end()

QtCore Module

48

--itr;
Ali

Mohamed

mylist

Mohsen

.
Sami

qDebug() << *(itr);

.) Sami (

qDebug() << *(--itr);


Ali

.) Mohsen (

Mohamed

qDebug() << *(--itr);


Ali

Mohamed

Mohsen

Sami

mylist

Mohsen

Sami

Mohamed

mylist

Mohsen

Sami

end()

end()

.) Modified (
Mohamed

mylist

Modified

Sami

................................................................................

49

end()

.) Mohsen (

*(itr) = Modified;

Ali

mylist

.) Mohamed (

qDebug() << *(++itr);


Ali

end()

QtCore Module

end()

foreach Keyword

:
foreach switch while for

( )
. ...
:
foreach (variable , container)
QDir , QFileInfo Example

#include <QtCore>
int main()
{
QList<QString> mylist;
mylist << Mohamed << Mahmoud << Ali << Omar;
foreach ( QString liststr , mylist )
qDebug() << liststr;

EX
Am
NO ple
15

QMap<QString , int> mymap;


mymap[ahmed] = 1;
mymap[mohamed] = 2;
mymap[osama] = 3;
foreach ( QString mapstr , mymap.keys() )
qDebug() << mapstr;

foreach ( int mapint , mymap.values() )


qDebug() << mapint;

QList<QString> mylist;
mylist << Mohamed << Mahmoud << Ali << Omar;
. QString mylist
foreach ( QString liststr , mylist )
qDebug() << liststr;

.QString liststr
. mylist liststr foreach
QtCore Module

50

;QMap<QString , int> mymap


;mymap[ahmed] = 1
;mymap[mohamed] = 2
;mymap[osama] = 3
mymap QString .int
) )(foreach ( QString mapstr , mymap.keys
;qDebug() << mapstr

mapstr . QString
foreach mapstr mymap .

) )(foreach ( int mapint , mymap.values


;qDebug() << mapint

mapint .int
foreach mapint mymap .

forever
:
{forever
...
}
{ } .
................................................................................

QtCore Module

51

QDir Class

:


:


( ) / ( \ )
.
.
1: QDir(/home/user/Documents) use in mac or linux.
2: QDir(C:/Documents and Settings) use in windwos.
( ) / ( \ )
.C:\Documents and Settings
( : ) Declaration

;)QDir name(dir name


;)EX: QDir mydir(C:\\windows

)cd(dir name
)mkdir(dir name
)mkpath(dir path
)(absolutePath
)entryInfoList(atrribute

.dir name
.dir name
.dir path
.
.attribute

................................................................................

52

QtCore Module

QFileInfo Class

:


:


.
QFileInfoList QFileInfo
>.QList<QFileInfo
( : ) Declaration

;)QFileInfo name(filepath/filename
;)EX: QDir mydir(c:\\mypath\\myfile.txt

)cd(dir name
)mkdir(dir name
)mkpath(dir path
)(absolutePath
)entryInfoList(atrribute

.dir name
.dir name
.dir path
.
.attribute



.
QDir, QFileInfo , QFileInfoList
.
................................................................................

QtCore Module

53

#include <QtCore>

QDir , QFileInfo Example

int main()
{
QDir mydir;
QFileInfoList flist;
mydir.cd(mydir.currentPath());
qDebug() << mydir.absolutePath();
mydir.mkdir( test );
mydir.cd( test );
mydir.mkdir( 1 );
mydir.cd( 1 );
mydir.mkdir( 2 );
mydir.cdUp();
mydir.cd( .. );
mydir.mkpath( test2/1/2 );
flist = mydir.entryInfoList(QDir::AllEntries ,QDir::Size);
QString d;
qDebug() << FileName << \t\t << Size << \t << Type\n;
foreach( QFileInfo f , flist )
{
if ( f.isDir() )
d = DIR;
else d = file;
qDebug() << f.fileName() << \t\t << f.size() << \t << d;
}
}

QDir mydir;
QFileInfoList flist;
mydir.cd(mydir.currentPath());
qDebug() << mydir.absolutePath();
mydir.mkdir(test);

EX
Am
NO ple
16

.flist mydir
. mydir
.
.test
QtCore Module

54

.test
.1
.1
.2
1 .test

;)mydir.cd(test
;)mydir.mkdir(1
;)mydir.cd(1
;)mydir.mkdir(2
;)(mydir.cdUp

;)mydir.cd(..
() cdUP ( cd).. .
.test2 / 1 /2

;)mydir.mkpath(test2/1/2

;)flist = mydir.entryInfoList(QDir::AllEntries ,QDir::Size


flist .QDir::Size
)foreach(QFileInfo f , flist
{
;if (f.isDir()) d = DIR
;else d = file
;qDebug() << f.fileName() << \t\t << f.size() << \t << d
}
.
QtCore Module

55

QFile Class

:
QIODevice

:
.

( : ) Declaration

;)QFile myfile(myfile.txt

)open(option
)read(length
)seek(length
)(readLine
)write(data

( option ).
length .
length.
.
data .

................................................................................

56

QtCore Module

#include <QtCore>

QFile Example
EX
Am
NO ple
17

int main()
{
QFile File(test.txt);
File.open(QIODevice::ReadWrite | QIODevice::Text);
File.write( Hi Qt Developer !!\n );
File.seek( 0 );
qDebug() << File.readLine();
}

File.close();

QFile File(test.txt);

.test.txt File

File.open(QIODevice::ReadWrite | QIODevice::Text);
.
File.write( Hi Qt Developer !!\n );
File.seek( 0 );

. Hi Qt Developer !!
. 0

qDebug() << File.readLine();


File.close();

57

QtCore Module

.
.

QTextStream Class

:


:
QIODevice ) Text (

QTextStream .QString QByteArray
. QIODevice QFile
: ) Declaration (
QTextStream mystream(QIODevice);
QTextStream mystream(QByteArray);
QTextStream mystream(QString);

:
. (<<) )>>(
QTextStream Example

#include <QtCore>

EX
Am
NO ple
18

int main()
{
QFile File(test.txt);
File.open(QIODevice::ReadWrite | QIODevice::Text);
QTextStream fstr( &File );
fstr << Hi Qt Developer !!\n;
fstr << 65;
fstr.seek( 0 );
qDebug() << fstr.readLine();
}

qDebug() << fstr.readLine();

QtCore Module

58

;)QFile File(test.txt
;)File.open(QIODevice::ReadWrite | QIODevice::Text
File .test.txt .
fstr .File

;) QTextStream fstr( &File


;fstr << Hi Qt Developer !!\n

!! Hi Qt Developer .

;fstr << 65

65 .

;) fstr.seek( 0

0 .

;)(qDebug() << fstr.readLine


;)(qDebug() << fstr.readLine
readLine .

................................................................................

QtCore Module

59

QDataStream Class

:


:
QIODevice

QDataStream QByteArray
. QIODevice QFile
: ) Declaration (
QDataStream mystream(QIODevice);
QDataStream mystream(QByteArray);

:
. (<<) )>>(
QDataStream Example

#include <QtCore>
int main()
{
QFile File(test.txt);
File.open(QIODevice::ReadWrite);

EX
Am
NO ple
19

QDataStream fdata(&File);
fdata << QString(Hi Qt Developer !!);
fdata << 65;
fdata.device()->seek( 0 );
QString str;
int a;
fdata >> str >> a ;
qDebug() << str << a ;
}

File.close();
QtCore Module

60

;)QFile File(test.txt
;)File.open(QIODevice::ReadWrite | QIODevice::Text
File .test.txt .
fdata .File
!! Hi Qt Developer .

;)QDataStream fdata(&File

;)!! fdata << QString(Hi Qt Developer


;fstr << 65

65 .

;) fdata.device()->seek( 0
0 . () fdata.device QFile
. seek
;QString str
;int a
; fdata >> str >> a
; qDebug() << str << a
(<<)
.

................................................................................

QtCore Module

61

QVariant Class

:


:


.
: ) Declaration (
QVariant myvar(any data type);

:
.
QVariant Example

#include <QtCore>
int main()
{
QVariant v( 100 );
int x = v.toInt() + 10;
QString str = v.toString();
double z = v.toDouble() * 0.2234;

EX
Am
NO ple
20

qDebug() << v.typeName() ;


qDebug() << x ;
qDebug() << str;
qDebug() << z ;
QVariant v1( 100 );
x = v1.toInt() + 10;
str = v1.toString();
z = v1.toDouble() * 0.2234;
qDebug() << v1.typeName() ;

qDebug() << x ;
qDebug() << str;
qDebug() << z;
QtCore Module

62

;) QVariant v( 100

v QVariant .100
x int 110 v .int

;int x = v.toInt() + 10

;)(QString str = v.toString


str QString 100 v .QString
;double z = v.toDouble() * 0.2234
z double 22.34 v .Double
; )(qDebug() << v.typeName
v int .
v1 .100

;) QVariant v1( 100


;x = v1.toInt() + 10
;)(str = v1.toString
;z = v1.toDouble() * 0.2234

; )(qDebug() << v1.typeName


v QString .

................................................................................

QtCore Module

63

( ) QtCore Module

150 .
QObject

.
Notes

............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................

64

QtCore Module

QObject Class

65

QObject Class

QObject Class

66

QObject Class

:


:


.

70 .
:
( .) parent
( .) children
( ) child ( ) parent .
.
( ) object ( ) QObject
.
( ) QObject ( ) events
( ) timer ( .) keyboard Events
( ) QObject ( ) Signals & Slots
.
( ) QObject Q_CLASSINFO
.Q_SIGNALS , Q_SLOTS , Q_PROPERTY , Q_OBJECT

( ) QObject

QObject Class

67

) parent ( ) QObject (
: ) child (
QObject *parent = new QObject();
QObject *child1 = new QObject(parent);
QObject *child2 = new QObject(parent);
QObject *child1_1 = new QObject(child1);
QObject *child2_1 = new QObject(child2);
QObject *child2_2 = new QObject(child2);

child1_1

child2_1

child1

child2

child2_2

parent
:
. child1 , child2 ) ( ) ( parent
.child1_1 ) ( ) ( child1
.child2_1 , child2_2 ) ( ) ( child2
. ( ) QObject
.child2_1 , child2_2 child2
................................................................................

QObject Class

68

QObject

( ) QObject ( ) meta object :
Class Name


Inheritance

Properties


Signals & Slots


Class Info

( ) Macro ++
( ) Compiler
++ .
Executable

Links

obj.o

Compiling

Source
.cpp
include

moc_*.cpp

MOC
Compile

Header
.h

( Meta Object Compiler ( moc ()headers


( .) QObject ( slots , signals
) etc moc_classname.cpp .++
:
moc ( )headers .Q_OBJECT
Q_OBJECT moc ( )moc_classname.cpp
.
Q_OBJECT Q_PROPERTY Q_SIGNALS , Q_SLOTS , .
.QObject
QObject Class

69

: QObject
class className : public QObject <----------- QObject
{
Q_OBJECT
<--Q_OBJECT
)Q_CLASSINFO(....
<-- Q_CLASSINFO
)Q_PROPERTY(.....
<-- Q_PROPERTY
public:
<--
constructor(QObject *parent, ...); <--
;)(setter functions
<--
;)(getter functions
<--
private:
<--
;variables
<--
.....

setter .getter
<--

protected:
...
Q_SLOTS:
;slots functions

<-- Q_SIGNALS

Q_SIGNALS:
;signals function
}

<-- Q_SLOTS
<--

<--

70

QObject Class


.
Q_OBJECT
( ) meta object compiler QObject
( .) moc
( ; )

Q_CLASSINFO


:
)Q_CLASSINFO(Programmer , Ali
)Q_CLASSINFO(about , drawing

Q_PROPERTY

:
( ) Setter Function ( .) Getter Function
Q_PROPERTY .Setter , Getter
:
) Q_PROPERTY( Var_datatype propertyName READ Getter WRITE Setter

class classname : QObject


{
Q_OBJECT
)Q_PROPERTY(int num_pro READ number WRITE setNumber
public:
)(int number
;)void setNumber(int
private:
;int num
;}

) setProperty( propertyName , Variable Value

Q_SLOTS & Q_SIGNALS

public , private , protected .

Q_OBJECT
.
QObject Class

71

Q_SIGNALS and Q_SLOTS



:
( ) Signal Function ( .) Slot Function
( ) Signal Function ( .) Signal Function
:
.Q_SIGNALS

( .Q_EMIT ( Signal Function : .Q_SLOTS
:
;))connect( obj1 , SIGNAL(signal function) , obj2 , SLOT(slot function
Function
)(doSomething
{
.......
;))(Q_EMIT(sendThing
}

Object 1
Function
)(doSomething
Q_SIGNALS
)(sendThing

;) ) )(connect ( Object1 , SIGNAL ( sendThing() ) , Object2 , SLOT ( accessRecv

Object 2
Q_SLOTS
)(accessRecv

: Container Watcher
.
72

QObject Class

container.h

#include <QObject>
#include <QStringList>
class container : public QObject <---
{
Q_OBJECT <---
public:
explicit container(QObject *parent = 0); <---
void addItem(QString); <---

.QObject container
EX
Am
NO ple
21

QObject container
Q_OBJECT


strlist

Q_SIGNALS: <--- Q_SIGNALS


void ItemAdded(QString); <--- QString


public Q_SLOTS: <--- Q_SLOTS

<---
private:
QStringList strlist; <--- strlist
};
#include container.h

container.cpp

container::container(QObject *parent) :
QObject(parent)
{ <---
}

void container::addItem(QString str) <--- strlist


{
this->strlist << str; <--- strlist str
Q_EMIT(ItemAdded(str)); <--- Q_EMIT

}
str ItemAdded Q_EMIT
.addItem
. ItemAdded

73

QObject Class

#include <QObject>

watcher.h

.QObject watcher

class watcher : public QObject


{
Q_OBJECT
public:
explicit watcher(QObject *parent = 0);
Q_SIGNALS:
public Q_SLOTS: <---
void printstr(QString); <---
};

Q_SLOTS

Q_SLOTS printstr
.connect ) signal function (

#include watcher.h
#include <QDebug>

watcher.cpp

watcher::watcher(QObject *parent) :
QObject(parent)
{
}
void watcher::printstr(QString str)
{
qDebug() << new Item was added to Container : << str;
}
: printstr
. printstr str :
. QString :
QObject Class

74

#include <QtCore/QCoreApplication>
#include container.h
#include watcher.h

main.cpp

.QObject watcher

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


{
QCoreApplication a(argc, argv);
container *cont = new container; <--- cont container
watcher *watch = new watcher; <--- watch watcher
QObject::connect(cont , SIGNAL(ItemAdded(QString)) , watch , SLOT(printstr(QString)));

cont->addItem(Mohamed 1);
cont->addItem(Mohamed 2);
cont->addItem(Mohamed 3);
return a.exec();

connect( cont , SIGNAL( ItemAdded(QString) ) , watch , SLOT( printstr(QString) ) );


cont ItemAdded
.watch printstr

:
.strlist cont addItem
Q_EMIT ItemAdded
.

watch printstr connect
.) (

:
new Item was added to Container : Mohamed 1
new Item was added to Container : Mohamed 2
new Item was added to Container : Mohamed 3

75

QObject Class

:signals and slots


( ) signal

( ) slot ( )
( ) .
:
signal function : setdata(int) <-- 1 int
1 slot function : execdata(int) <--- int
.

:
.

: .
:
.
connect

Slots
)execdata(int
)execdata(QString,int
)execdata(int,QString
)(execdata
)(execdata
)setdata(int
)setdata(int,int

)execdata(int

Signals

)setdata(int
)setdata(int,QString
)setdata(int,QString
)(setdata
)setdata(int
)setdata(int,int
)setdata(int
)(setdata

.QObject
:
.
.
.
76

QObject Class

Inherits
car
Macros , Constructors and Destructors
ClasName

Level
NON
NON
NON
NON
NON
public
public

Type
Macro
Macro
Macro
Macro
Macro
Contructor
Contructor

Level
private
private
private
private
private

Type
QString
QString
int
int
bool

Variables

Function member

Q_OBJECT
Q_CLASSINFO(Author , QT-Developer)
Q_PROPERTY(QString carname READ name WRITE setName);
Q_PROPERTY(QString carmodel READ model WRITE setModel)
Q_PROPERTY(int carspeed READ speed WRITE setSpeed)
explicit car(QObject *parent = 0);
explicit car(QString name, QObject *parent = 0);
Name

Info

car_name;
car_model;
car_speed;
car_maxspeed;
car_enginestatus;

Setters and Getter Function members


Level
public
public
public
public
public

Setters Functions
Type
Function
void
setName(QString);
void
setModel(QString);
void
setMaxSpeed(int);
void
StartEngine();
void
StopEngine();

Level
public
public
public
public
public
public

Slots and Signals


Level
Q_SLOTS

77

Q_SLOTS
Type
Function
void
setSpeed(int);

QObject Class

QObject

Level
Q_SIGNALS
Q_SIGNALS
Q_SIGNALS

Getters Functions
Type
Function
QString name();
QString model();
int
speed();
int
maxSpeed();
bool
isEngineOn();
QString EngineStatus();
Q_SIGNALS
Type
Function
void SpeedChanged(int);
void Enginetoggled(bool);
void MaxSpeed(int);
:

:) car.h (

#include <QObject>
class car : public QObject
{
Q_OBJECT
Q_CLASSINFO(Author , QT-Developer)
Q_PROPERTY(QString carname READ name WRITE setName)
Q_PROPERTY(QString carmodel READ model WRITE setModel)
Q_PROPERTY(int carspeed READ speed WRITE setSpeed)
public:
explicit car(QObject *parent = 0);

explicit car(QString name, QObject *parent = 0);
void setName(QString);
void setModel(QString);
void setMaxSpeed(int);
Setters
void StartEngine();
void StopEngine();
QString name();
QString model();
int speed();
Getters
int maxSpeed();
bool isEngineOn();
QString EngineStatus();
Q_SIGNALS:
void SpeedChanged(int);
void Enginetoggled(bool);
void MaxSpeed(int);
public Q_SLOTS:

void setSpeed(int);
private:
QString car_name;
QString car_model;

int car_maxspeed;
int car_speed;
bool car_enginestatus;
};

}
}

QObject Class

78

:
.
Q_OBJECT moc .QObject

Q_OBJECT
Q_CLASSINFO

:
)Q_CLASSINFO(Author , QT-Developer
)Q_CLASSINFO(Web , www.carclass.net
Q_PROPERTY
( ) Variable Type ( ) Getter Function
( .) Setter Function
:
)Q_PROPERTY(DataType PropertyName READ GetterFunction WRITE SetterFunction
. Q_PROPERTY
:
)Q_PROPERTY(QString carname READ name WRITE setName
)Q_PROPERTY(QString carmodel READ model WRITE setModel
)Q_PROPERTY(int carspeed READ speed WRITE setSpeed
Q_SIGNALS
Q_SIGNALS void
. classname.cpp
. Q_EMIT
Q_SLOTS
Q_SLOTS
.Q_SIGNALS

................................................................................

QObject Class

79

#include car.h
car::car(QObject *parent) :
QObject(parent)
{
this->car_speed = 0;
this->car_enginestatus = false;
}

car ) car.cpp (

car::car(QString name, QObject *parent):QObject(parent)


{
this->car_speed = 0;
this->car_enginestatus = false;
this->car_name = name;
}
void car::setName(QString name)
{
this->car_name = name;
}
void car::setModel(QString model)
{
this->car_model = model;
}
void car::setMaxSpeed(int max)
{
this->car_maxspeed = max;
Q_EMIT MaxSpeed(max);
}

}
}
}

: Setter

: Setter

: Setter

<------------ MaxSpeed Q_EMIT

max

QObject Class

80

void car::setSpeed(int speed)


{
if(speed < 0)speed = 0;
if(speed > this->car_maxspeed) speed = this->car_maxspeed;
: Setter
if(this->car_speed == speed)return;
if(!this->isEngineOn())speed=0;
this->car_speed = speed;
Q_EMIT
Q_EMIT SpeedChanged(speed); <----------------------------- SpeedChanged
speed
}

void car::StartEngine()
{
: Setter
if(this->car_enginestatus == true) return;
this->car_enginestatus = true;
Q_EMIT
Q_EMIT Enginetoggled(this->car_enginestatus); <------ Enginetoggled
}
car_enginestatus

void car::StopEngine()
{
if(this->car_enginestatus == false) return;
: Setter
else{
this->setSpeed(0);
Q_EMIT
this->car_enginestatus = false;
Q_EMIT Enginetoggled(this->car_enginestatus); <------ Enginetoggled
car_enginestatus
}
}
QString car::name()
{
return this->car_name;
}
QString car::model()
{
return this->car_model;
}

81

QObject Class

}
}

: Getter

: Getter

: Getter

: Getter

: Getter bool : true , false

: Getter QString

}
}
}

)(int car::maxSpeed
{
;return this->car_maxspeed
}
)(int car::speed
{
;return this->car_speed
}
)(bool car::isEngineOn
{
;return this->car_enginestatus
}

)(QString car::EngineStatus
{
;QString status
;if(this->isEngineOn()) status = Engine On
;else status = Engine Off
;return status
}

signals and slots QObject



slots .Q_SLOTS
:



;)>void on_<object name>_<signal name>(<signal parameters
;)(EX : void on_PushBotton_clicked

connectSlotsByName
.
QObject Class 82

QtGui Module

QtGui Module

83

>#include <QtGui

QT += gui
. project.pro

84

QtGui Module

GUI :



: () Buttons , Line Edit , Radio Buttons
( ) Events
.

QWidget
( .) Events
QWidget ( ) QObject , QPaintDevice
QObject QPaintDevice.
QWidget
.
................................................................................

QtGui Module

85

QWidget Class

:
QPaintDevice , QObject

:


( ) Gui module
( .) Events
:
QWidget .

:
) QWidget( QWidget *parent = 0, Qt::WindowFlags f = 0

QWidget . parent , f
parent 0 .
parent 0
QWidget ( .) window

parent widget
QWidget .widget

mywidget

QWidget mywidget(0); <--------

mywidget

QWidget mywidget; <--------

;) QWidget mywidget2( &mywidget


mywidget2 mywidget . mywidget

parent children
.
86

QtGui Module

#include <QtGui/QApplication>
#include <QWidget>
#include <QLabel>
#include <QLineEdit>
#include <QCheckBox>

main.cpp

EX
Am
NO ple
22

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


{
QApplication a(argc, argv);
QWidget wid;
QLabel lbl;
QLineEdit line;
QCheckBox box;
wid.show();
lbl.show();
line.show();
box.show();
return a.exec();
}

. :
QWidget wid
QLabel lbl

QCheckBox box
QLineEdit line

87

QtGui Module

>#include <QtGui/QApplication
>#include <QWidget
>#include <QLabel
>#include <QLineEdit
>#include <QCheckBox
)][int main(int argc, char *argv
{
;)QApplication a(argc, argv
;QWidget wid
;)QLabel lbl(&wid
;)QLineEdit line(&wid
;)QCheckBox box(&wid
;)(wid.show
;)(return a.exec
}

lbl,line,box wid wid


.wid
.
Qt Designer

signals and slots . Qt Designer
QWidget
( ) setGeometry
( ) show , hide .
QWidget
Qt Creator
.
88

QtGui Module

.Qt Creator

- New File or Project .File

- Qt c++ Project Qt Gui Application .Project

- .test

QtGui Module

89

- : class information QWidget . base class

Run . Qt Creator . Qt Creator:

Project
|---test.pro <---
|---Forms <---
|
|----widget.ui <---Qt Designer
|
|---Headers
|
|----widget.h <---
|
|---Source
|----main.cpp <---
|----widget.cpp <---
90

QtGui Module

Qt Creator ( ) Folder

test
.
: test.pro
( ) Modules

( ) gui , network .

: widget.ui
.

: main.cpp
.

: widget.h
.widget

: widget.cpp
.widget

build all :
widget.ui ui_widget.h .uic
uic

.namespace


moc QObject .moc_widget.cpp

. : ( .) moc_widget.cpp , ui_widget.h
.widget.h , widget.cpp , main.cpp
QtGui Module

91

main.cpp

>#include <QtGui/QApplication
#include widget.h

Main int main(int argc, char *argv[]) <------


{
QApplication a(argc, argv); <------
Widget Widget w; <------ QWidget

.
w.show(); <------
return a.exec(); <------

widget.h
:
: namespace
.ui_widget.h :
;)* setupUi(QWidget
;)retranslateUi(QWidget *Widget
setupUi
:
Ui::Widget
retranslateUi
.................................................
: .QWidget

#ifndef WIDGET_H
#define WIDGET_H
>#include <QWidget
{ namespace Ui
;class Widget
}
class Widget : public QWidget
{
Q_OBJECT
public:
;)explicit Widget(QWidget *parent = 0
;)(~Widget

ui Ui::Widget

92

QtGui Module

private:
;Ui::Widget *ui
;}
#endif // WIDGET_H

widget.cpp

#include widget.h
#include ui_widget.h

Widget::Widget(QWidget *parent) :
QWidget(parent),
)ui(new Ui::Widget
{
;)ui->setupUi(this
}
)(Widget::~Widget
{
;delete ui
}

ui_widget.h
(
) .
Ui_Widget
retranslateUi , setupUi
: setupUi .
: retranslateUi
.

class Ui_Widget
{
public:
{ )void setupUi(QWidget *Widget

......
}

{ )void retranslateUi(QWidget *Widget



.......
}
;}
Ui::Widget Ui_Widget
. retranslateUi , setupUi
Ui::Widget widget.h

{ namespace Ui
;}{ class Widget: public Ui_Widget
}

QtGui Module

93



signals and slots .
car QObject

:
main.cpp <-----
car.h <----- car
car.cpp <----- car
car_gui QWidget .
car_gui.h <----- car_gui
car_gui.cpp <----- car_gui
( ) EX_QObject_car
.Qt Designer
ObjectName:
namelbl
ObjectName:
modelbl
ObjectName:
enginestatuslbl

8 QLabel
Class

ObjectName:
speedlbl

QDail Class

ObjectName:
speeddail

94

QtGui Module

QToolButton Class

ObjectName:
enginebtn

car_gui.h

#ifndef CAR_GUI_H
#define CAR_GUI_H

EX
Am
NO ple
23

#include <QWidget>
#include car.h <-------- car
namespace Ui {
class car_gui; <-------- Ui::car_gui
}
class car_gui : public QWidget
{
Q_OBJECT
public:
explicit car_gui(QWidget *parent = 0);
~car_gui();
car *toyota;
public Q_SLOTS:
void setCarSpeed(int);
void setCarEngine(bool);
private:
Ui::car_gui *ui;
};

#endif // CAR_GUI_H

car_gui

:


.

95

QtGui Module

#include car_gui.h
#include ui_car_gui.h
#include car.h

car_gui.cpp

car_gui::car_gui(QWidget *parent) :
QWidget(parent),
ui(new Ui::car_gui)
{
QString str;
ui->setupUi(this);
toyota = new car(this);
toyota->setProperty(carname , TOYOTA);
toyota->setModel(2005);
toyota->setMaxSpeed(200);
ui->speeddial->setMaximum(toyota->maxSpeed());
ui->namelbl->setText(toyota->name());
ui->modelbl->setText(toyota->property(carmodel).toString());
ui->enginestatuslbl->setText(toyota->EngineStatus());
str.setNum(toyota->speed());
ui->speedlbl->setText(str);
connect(toyota , SIGNAL(SpeedChanged(int)), this , SLOT(setCarSpeed(int)));
connect(toyota ,SIGNAL(Enginetoggled(bool)),this,SLOT(setCarEngine(bool)));

connect(ui->speeddial,SIGNAL(valueChanged(int)),toyota,SLOT(setSpeed(int)));
connect(ui->enginebtn,SIGNAL(clicked(bool)) , this,SLOT(setCarEngine(bool)));

car_gui::~car_gui()
{
delete ui;
}
QtGui Module

96

void car_gui::setCarSpeed(int speed)


{
QString str;
str.setNum(speed);
ui->speedlbl->setText(str);
ui->speeddial->setValue(speed);
}
void car_gui::setCarEngine(bool status)
{
if (status == true)
{
toyota->StartEngine();
ui->enginestatuslbl->setText(toyota->EngineStatus());
ui->enginebtn->setText(Stop Engine);
}
else
{
toyota->StopEngine();
ui->enginestatuslbl->setText(toyota->EngineStatus());
ui->enginebtn->setText(Start Engine);
}
}
.signals and slots ) connect (

97

car class

car_gui class

Q_SIGNALS

Q_SIGNALS

SpeedChanged(int)
Enginetoggled(bool)

ui->speeddial::valueChanged(int)
ui->enginebtn:: clicked(bool)

Q_SLOTS

Q_SLOTS

setSpeed(int)

setCarSpeed(int)
setCarEngine(bool)

QtGui Module

car_gui

QObject Signals and Slots
connectSlotsByName
: slot
void on_<object name>_<signal name>(<signal parameters>);
:
: car_gui.h

class car_gui : public QWidget


{
.....
public Q_SLOTS:

.....
void on_mycarname_SpeedChanged(int); on_mycarname_SpeedChanged(int)
Q_SLOTS
...
car mycarname
}

: car_gui.cpp

car_gui::car_gui(QWidget *parent) :QWidget(parent),ui(new Ui::car_gui)


{
....
.car mycarname
toyota = new car(this);
toyota->setObjectName(mycarname);
...
SpeedChanged connect
// connect(toyota , SIGNAL(SpeedChanged(int)), this , SLOT(setCarSpeed(int)));
....
QMetaObject::connectSlotsByName(this);
}

.
on_<object name>_<signal name>(<signal parameters>).

void car_gui::on_toyota_SpeedChanged(int i )
{
setCarSpeed( i);
}

connect
.

QtGui Module

98


QWidget
( .) Events
: QWidget
( : ) Event Function



( ) drag and drop .
:
-1 ( ) class.h .protected

-2 ( ) implement code ( .) class.cpp

(* .keyPressEvent(QKeyEvent .shift

-1 : class.h

-2 : class.cpp

class classname
{
.....
protected:
;)* void keyPressEvent(QKeyEvent
;}

)void classname::keyPressEvent(QKeyEvent *key


{
)if(key->key() == Qt::Key_Shift

{

do somthing.....

}
}
QtGui Module

99

( : ) Event Filter Function


.
:
-1 installEventFilter .

-2 ( ) class.h .protected

-3 ( ) implement code ( .) class.cpp

:
-1 :class.cpp

textEdit

-2 : class.h

-3 : class.cpp

{ )classname:: classname(..
;)ui->textEdit->installEventFilter(this
}

class classname
bool void
( )
{
1
.....
true false
protected:
;)* bool eventFilter(QObject *, QEvent
;}
{ )bool classname::eventFilter(QObject *obj, QEvent *event
textEdit .
{ )if (obj == ui->textEdit
KeyPress
{ )if (event->type() == QEvent::KeyPress
;)QKeyEvent *ke = static_cast<QKeyEvent *>(event
A ;if (ke->key() == Qt::Key_A) return true
true
;else return false
A textEdit
}
false
.
}
;)return QWidget::eventFilter(this,event
}

100

QtGui Module

QWidget
QWidget paintEvent

QWidget ( Event )
QPainter
. QWidget
QWidget
paintEvent protected widget.h
QPainter paintEvent .widget.cpp

widget.h

EX
Am
NO ple
24

>#include <QWidget

class Widget : public QWidget


{
Q_OBJECT
......
protected:
void paintEvent(QPaintEvent *); <------ paintEvent
......
;}

widget.cpp
<------ paintEvent

)void Widget::paintEvent(QPaintEvent *p

{
pp QPainter pp(this); <------ QPainter
pen QPen pen; <------ QPen
color QColor color(10,100,100); <------ QColor
pen.setColor(color); <------
color pen
pen pp

pp.setPen(pen); <------
pp.save(); <------
QtGui Module

101

widget.cpp
( ) 0 0 (pp.translate(100,100); <------ (100 100
( ) 0 0 ( pp.drawLine(0,0,100,0); <------ ( 0 100
( pp.translate(100,0); <------ (0 100
90 pp.rotate(90); <------
( ) 0 0 ( pp.drawLine(0,0,100,0); <------ ( 0 100
;)pp.translate(100,0
;)pp.rotate(90
;)pp.drawLine(0,0,100,0
;)pp.translate(100,0
;)pp.rotate(90
;)pp.drawLine(0,0,100,0
pp.restore(); <------
br QBrush br; <------ QBrush
color br.setColor(color); <------ br
br.setStyle(Qt::Dense7Pattern); <------
pp.fillRect(0,0,100,100,br); <------ br
Pen Width pen.setWidth(3); <------ 3
pp.setPen(pen); <------ pen
pp.drawEllipse(100,0,100,100); <------
pp.setRenderHint(QPainter::Antialiasing , true); <------
pp.drawEllipse(200,0,100,100); <------
}
Antialiasing .

QPainter .

102

QtGui Module

QPainter Class

:


:
.QWidget

( : ) Declaration

;) QPainter mypaint( QPaintDevice * device


QPainter QPaintDecice

QWidget .
:
:

( : ) Settings ) .
(
( : ) Drawing .
( : ) Rendering Quality .Antialiasing
( :) Coordinate Transformations ( ) Scale ( ) Rotate
( ) Translate ( ) save

( ) restore .

QtGui Module

103

QDialog Class

:
QWidget

:
QWidget


:
( .) Modal Dialogs , Modeless Dialogs
( : ) Modal Dialogs


Accepted .Rejected
:
( ) Open File

( .) Ok , Cancel
( :) Modeless Dialogs


.
:
( ) Find ( ) Replace .

( : ) Declaration
.

;)QDialog mydialog( QWidget * parent = 0
:
() exec

Accepted .Rejected
Accepted Ok Enter . Rejected Cancel ESC .104

QtGui Module

: Qwidget Modal Dialog


.
QtCreator .widget

ObjectName:

retvallbl

ObjectName:

opendlgbtn
: newfile or project file
Qt Designer Form Class Files And Classes
Dialog with Buttons
.myDialog

ObjectName:

sendldt
QtGui Module

105

Qt Creator

.
... <-------widget.h
EX
Am
#include mydialog.h
NO ple
25
...
class Widget : public QWidget
{
.....
private slots:
void on_opendlgbtn_clicked();
...
};
on_opendlgbtn_clicked
opendlgbtn clicked
void Widget::on_opendlgbtn_clicked() <-------widget.cpp
{
myDialog mydlg(this);
if(mydlg.exec() == true)
ui->retvallbl->setText(mydlg.retval());
}
. ) opendlgbtn ( ) clicked (
myDialog mydlg(this);
.myDialog mydlg
if(mydlg.exec() == true)
ui->retvallbl->setText(mydlg.retval());
.cancel false ok true mydlg.exec
QtGui Module

106

class myDialog : public QDialog <-------mydialog.h


{
..
public:
...
QString retval();
...
};
QString myDialog::retval()
{
return this->ui->sendldt->text();
}

<-------mydialog.cpp

.QLineEdit sndldt retval


................................................................................
.Modal Dialog QDialog
Modeless Dialog QDialog
: exec)(
void Widget::on_opendlgbtn_clicked() <-------widget.cpp
{
myDialog *mydlg = new myDialog (this);
mydlg->show();
}
................................................................................

107

QtGui Module

QMainWindow Class

:
QWidget

:
:

.Menu Bar QMenuBar .QWidget

.Tool Bar QToolBar .QWidget

.Status Bar QStatusBar .QWidget

.Dock Widget QDockWidget .QWidget

.Central Widget .QWidget

108

QtGui Module

Menu Bar
QWidget QMenuBar


.QAction QMenuBar
Open , Save , Save as File :
.new File1 , new File2 New
:

actionNew_File1 = new QAction(MainWindow);


actionNew_File2 = new QAction(MainWindow);
actionOpen = new QAction(MainWindow);
actionSave = new QAction(MainWindow);
actionSave_as = new QAction(MainWindow);
menuBar = new QMenuBar(MainWindow);
menuFile = new QMenu(menuBar);
menuNew = new QMenu(menuFile);
MainWindow->setMenuBar(menuBar);
menuBar->addAction(menuFile->menuAction());
menuFile->addAction(menuNew->menuAction());
menuFile->addAction(actionOpen);
menuFile->addAction(actionSave);
menuFile->addAction(actionSave_as);
menuNew->addAction(actionNew_File1);
menuNew->addAction(actionNew_File2);

109

QtGui Module

}
}

EX
Am
NO ple
26

Tool Bar
QWidget QToolBar

QAction
.
:

actionNew_File1 = new QAction(MainWindow);


actionNew_File2 = new QAction(MainWindow);
actionOpen = new QAction(MainWindow);
actionSave = new QAction(MainWindow);
actionSave_as = new QAction(MainWindow);

mainToolBar = new QToolBar(MainWindow);


MainWindow->addToolBar(Qt::TopToolBarArea, mainToolBar);
mainToolBar->addAction(actionOpen);
mainToolBar->addAction(actionSave);
mainToolBar->addAction(actionSave_as);
mainToolBar->addAction(actionNew_File1);
mainToolBar->addAction(actionNew_File2);

Status Bar
QWidget QStatusBar

showMessage
.clearMessage
. :
QtGui Module

110

Dock Widget
QDockWidget QWidget

QWidget
.MainWindow
Qt::LeftDockWidgetArea
Qt::RightDockWidgetArea
Qt::TopDockWidgetArea
Qt::BottomDockWidgetArea
:
;)QDockWidget *docw = new QDockWidget(MainWindow
;)MainWindow->addDockWidget(Qt::RightDockWidgetArea , docw
Central Widget
QWidget

QWidget MainWindow Central widget
;)mainwindow->setCentralWidget(QWidget *mywidget
: mainwindow
( .SDI ( Single Document Interface
( .MDI ( Multiple Document Interface
: SDI


QWidget CentralWidget.
: MDI


QMdiArea CentralWidget.
: MainWindows
.Qt Designer
QtGui Module

111

( SDI ( Single Document Interface

( MDI ( Multiple Document Interface

112

QtGui Module


Layout Managment

113

Layout Managment

Layout Managment

114




GUI
:
.Object Geometry
.Layout
.Size Policy
:Object Geometry
( QWidget )


( ) Pixel .
.

) setGeometry ( int x, int y, int w, int h
x , y
w

h

) setMaximumHeight ( int maxh
maxh
maxw
minh
minw

) setMaximumWidth ( int maxw

) setMinimumHeight ( int minh

) setMinimumWidth ( int minw

Layout Managment

115

:Layout




:
.Horizontal Layout


.Vertical Layout


.Grid Layout


.Form Layout
: Horizontal Layout
QHBoxLayout

.
:
EX
Am
NO ple
27

QWidget *window = new QWidget; <------- window


;)QPushButton *button1 = new QPushButton(One
;)QPushButton *button2 = new QPushButton(Two
;)QPushButton *button3 = new QPushButton(Three

;)QPushButton *button4 = new QPushButton(Four
;)QPushButton *button5 = new QPushButton(Five

QHBoxLayout *layout = new QHBoxLayout; <------- layout


;)layout->addWidget(button1
;)layout->addWidget(button2

;)layout->addWidget(button3
;)layout->addWidget(button4
;)layout->addWidget(button5
layout window->setLayout(layout); <-------window
;)(window->show

116

Layout Managment

: Vertical Layout
QVBoxLayout

.
: QHBoxLayout .QVBoxLayout
: Grid Layout
QGridLayout

.
.

;)addWidget ( QWidget * widget, int row, int column

: Form Layout
QFormLayout


:

;) addRow ( const QString & labelText, QWidget * field


;) setWidget ( int row, ItemRole role, QWidget * widget

Layout Classes

.
;QHBoxLayout *H1_layout = new QHBoxLayout
;QHBoxLayout *H2_layout = new QHBoxLayout
;QVBoxLayout *V_layout = new QHBoxLayout
;)V_layout ->addLayout(H1_layout
;)V_layout ->addLayout(H2_layout

Layout
SizeHint .Size Policy
Layout Managment

117

:Size Policy


QSizePolicy
:
) setSizePolicy ( QSizePolicy
:QSizePolicy
;QSizePolicy sizePolicy
sizePlolicy .QSizePolicy
) sizePolicy. setHorizontalPolicy ( Policy policy
policy .
) sizePolicy. setVerticalPolicy ( Policy policy
policy .
;)sizePolicy.setHorizontalStretch(uchar stretchFactor
stretchFactor .
;)sizePolicy.setVerticalStretch(uchar stretchFactor
stretchFactor .

policy stretchFactor
................................................................................
118

Layout Managment

:Policies
Layout


SizeHint
.SizeHint

SizeHint
QSizePolicy::Fixed
.SizeHint
SizeHint
QSizePolicy::Minimum

.SizeHint
SizeHint
QSizePolicy::Maximum

.SizeHint
SizeHint
QSizePolicy::Preferred

( .SizeHint )QWidget
SizeHint
QSizePolicy::Expanding

.
SizeHint
QSizePolicy::MinimumExpanding
.
SizeHint
QSizePolicy::Ignored
.

................................................................................

Layout Managment

119

:stretchFactor
( ) stretchFactor 0

.
( ) stretchFactor X 1
Y 2
Y .X

. Qt Designer
Notes

............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................

120

Layout Managment


Drag and Drop

Drag and Drop

121

122

Drag and Drop

Drag And Drop




( ) object ( ) mouse
( ) object .
:
( .) Drag ( .) Drop



.) Multipurpose Internet Mail Extensions ) MIME
MIME


( ) ( )
.MIME

:

.
.
.
Event

QWidget
( ) Events
.QWidget
................................................................................
Drag and Drop

123

dragEnterEvent
dragLeaveEvent
dragMoveEvent
dropEvent


QDragEnterEvent .
QDragLeaveEvent .
QDragMoveEvent .
.
QDropEvent

MIME


( ) text/plain ( ...) image/jpeg

.
: MIME
http://www.iana.org/assignments/media-types/

:
:


.MIME

:
MIME

.

................................................................................

124

Drag and Drop

.Drag and Drop


QLabel .
QWidget .Qt Designer

Box 1:

Class : QLabel.

ObjectName : label.
Box 2:

Class : QLabel.

ObjectName : label_2.
Box 3:

Class : QLabel.

ObjectName : label_3.
................................................................................
Drag and Drop

125

#ifndef WIDGET_H
#define WIDGET_H

widget.h

EX
Am
NO ple
28

#include <QWidget>
#include <QLabel>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
QWidget *DragedLabel; <-----QLabel *DropedLabel; <------

QLabel
QLabel

private:
Ui::Widget *ui;
protected:
void mousePressEvent(QMouseEvent *); <------
void dragEnterEvent(QDragEnterEvent *); <------
void dropEvent(QDropEvent *); <------
};
#endif // WIDGET_H

Drag and Drop

126

widget.cpp

#include widget.h
#include ui_widget.h
#include <QMouseEvent>
#include <QStringList>
Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget)
{
ui->setupUi(this);
this->setAcceptDrops(true);
<------
}
Widget::~Widget()
{
delete ui;
}
void Widget::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton)
{
DragedLabel = childAt(event->pos());
if(!DragedLabel) return;
if (DragedLabel->inherits(QLabel) == true)
{
QString labelName = DragedLabel->objectName() ;
QString labelText = static_cast<QLabel*> (DragedLabel)->text();
QString transferText = labelName + --- + labelText;
QDrag *drag = new QDrag(this);
QMimeData *mimeData = new QMimeData;

127

mimeData->setText(transferText);
drag->setMimeData(mimeData);
drag->exec();

Drag and Drop

void Widget::dragEnterEvent(QDragEnterEvent *event)


{
if (event->mimeData()->hasFormat(text/plain))
event->acceptProposedAction();
}
void Widget::dropEvent(QDropEvent *event)
{
QStringList strlist;
strlist = event->mimeData()->text().split(---);
DropedLabel = this->findChild<QLabel *>(strlist[0]);
DropedLabel->setGeometry( event->pos().x()-75,event->pos().y()-25,150,50 );
DropedLabel->setText(strlist[1]);
}

event->acceptProposedAction();

void Widget::mousePressEvent(QMouseEvent *event)


.
if (event->button() == Qt::LeftButton)

DragedLabel = childAt(event->pos());
event->pos)( event->pos)( DragedLabel
childAt X,Y
.( )
if(!DragedLabel) return;
. DragedLabel
Drag and Drop

128

if (DragedLabel->inherits(QLabel) == true)
.QLabel DragedLabel
QString labelName = DragedLabel->objectName() ;
QString labelText = static_cast<QLabel*> (DragedLabel)->text();
QString transferText = labelName + --- + labelText;
( MIME
: )
. label_2---Box 2 label_2
QDrag *drag = new QDrag(this);

.QDrag drag

QMimeData *mimeData = new QMimeData;


.QMimeData mimeData
mimeData->setText(transferText);
.text/plain .mimeData
drag->setMimeData(mimeData);
. mimeData mimeData
drag->exec();

.
..................................................................................................................
void Widget::dragEnterEvent(QDragEnterEvent *event)
. ) (
if (event->mimeData()->hasFormat(text/plain))
event->acceptProposedAction();
.text/plain MIME
.

129

Drag and Drop

void Widget::dropEvent(QDropEvent *event)


. ) (
QStringList strlist;

.QStringList strlist

strlist = event->mimeData()->text().split(---);
. event->mimeData()->text)(
: split)---( label_2---Box 2
.) objectname ( strlist[0]= label_2
.) objecttext ( strlist[1]= Box 2
DropedLabel = this->findChild<QLabel *>(strlist[0]);
.MIME ) objectname ( DropedLabel
DropedLabel->setGeometry( event->pos().x()-75,event->pos().y()-25,150,50 );
. X,Y
DropedLabel->setText(strlist[1]);
event->acceptProposedAction();

.
.

................................................................................

Drag and Drop

130

/
Model/View programmig

131

Model/View Programming

Model/View Programming

132

/ ( ) Model / View Programming



.
( ) 4.4

4.4
/.




.
/ :
.Models
.Views
.QModelIndex
Data

Index

Model

tin
g
Ed
i
View

Model/View Programming

133




( . ) Signals and Slots
:Models
QAbstractItemModel


.
:
.List Model .Table Model- .Tree Model



.
134

Model/View Programming

QAbstractItemModel

:
: QStringListModel
.QString

: QStandardItemModel


QStandardItem .

: QFileSystemModel
.

: QSqlQueryModel, QSqlTableModel, and QSqlRelationalTableModel
( .) SQL


( ) Model

QAbstractItemModel .
................................................................................

Model/View Programming

135

:Views
QAbstractItemView

( ) Models
:
: QListView
.

: QTableView


.

: QTreeView


.

136

Model/View Programming

: QModelIndex
QModelIndex

Model .
Models Classes

( Row Column ) root ()QModelIndex
.

;) QModelIndex index = model->index( Row , Column , root

= QModelIndex indexA

;))(model->index(0, 0, QModelIndex
indexA A 0 .0
= QModelIndex indexB

;))(model->index(1, 1, QModelIndex
indexB B 1 .1
= QModelIndex indexC

;))(model->index(2, 1, QModelIndex
indexC C 2 .1
= QModelIndex indexA

;))(model->index(0, 0, QModelIndex
indexA A 0 .0
= QModelIndex indexC

;))(model->index(2, 1, QModelIndex
indexC C 2 .1
= QModelIndex indexB

;)model->index(1, 0, indexA
indexB B 1 0
.indexA
Model/View Programming

137

/

QWidget Qt Creator
.widget.cpp
#include widget.h
#include ui_widget.h
#include <QStringListModel>
#include <QListView>
#include <QStandardItem>
#include <QModelIndex>

widget.cpp

: :
EX
Am
NO ple
29

Widget::Widget(QWidget *parent) :QWidget(parent),ui(new Ui::Widget)


{
ui->setupUi(this);
QStringList strlist;
strlist << mohamed << ali << ahmed << samier << sami;
QStringListModel *mymodel = new QStringListModel;
mymodel->setStringList(strlist);
QListView *myview = new QListView(this);
myview->setModel(mymodel);
QModelIndex myindex;
mymodel->insertRow(mymodel->rowCount());
myindex = mymodel->index(mymodel->rowCount()-1);
mymodel->setData(myindex,new item inserted);

myindex = mymodel->index(2);
mymodel->setData(myindex, item modified);
Model/View Programming

138

QStringList strlist;
strlist << mohamed << ali << ahmed << samier << sami;
.QString
QStringListModel *mymodel = new QStringListModel;
QStringListModel mymodel
.
mymodel->setStringList(strlist);
0
1
2
3
4

.mymodel strlist

mohamed
ali
ahmed
samier
sami

QListView *myview = new QListView(this);


. QListView myview
myview->setModel(mymodel);
. myview mymodel
QModelIndex myindex;
. QModelIndex myindex
mymodel->insertRow(mymodel->rowCount());
.mymodel
0
1
2
3
4

mohamed
ali
ahmed
samier
sami

139

Model/View Programming

myindex = mymodel->index(mymodel->rowCount()-1);
.mymodel myindex

myindex

0
1
2
3
4

mohamed
ali
ahmed
samier
sami

mymodel->setData(myindex,new item inserted);


. myindex new intem inserted
0
1
2
3
4

myindex

mohamed
ali
ahmed
samier
sami
new item inserted

myindex = mymodel->index(2);
.. 2 1 0 2 myindex
myindex

0
1
2
3
4
5

mohamed
ali
ahmed
samier
sami
new item inserted

mymodel->setData(myindex, item modified);


. myindex item modified
myindex

0
1
2
3
4

mohamed
ali

new item inserted

samier
sami
Model/View Programming

140

#include widget.h
#include ui_widget.h
#include <QStandardItemModel>
#include <QTableView>
#include <QStandardItem>
#include <QModelIndex>

widget.cpp

: :
EX
Am
NO ple
30

Widget::Widget(QWidget *parent) :QWidget(parent),ui(new Ui::Widget)


{
ui->setupUi(this);
QList<QStandardItem*> itemlist;
itemlist << new QStandardItem(append 1);
itemlist << new QStandardItem(append 2);
itemlist << new QStandardItem(append 3);
itemlist << new QStandardItem(append 4);
QStandardItemModel *mymodel = new QStandardItemModel;
mymodel->setColumnCount(3);
for(int i = 0 ; i < 6 ;i++)
{
for(int j = 0 ; j < mymodel->columnCount() ;j++)
{
mymodel->setItem(i,j,new QStandardItem( QString(member %0,%1).arg(i).arg(j) ));
}
}

mymodel->appendRow(itemlist);
QTableView *myview = new QTableView(this);
myview->setGeometry(0,0,500,300);
myview->setModel(mymodel);
QModelIndex myindex;
myindex = mymodel->index(2,2);
mymodel->setData(myindex,modified);

141

Model/View Programming

QList<QStandardItem*> itemlist;
itemlist << new QStandardItem(append
itemlist << new QStandardItem(append
itemlist << new QStandardItem(append
itemlist << new QStandardItem(append


1);
2);
3);
4);
.QStandardItem

QStandardItemModel *mymodel = new QStandardItemModel;


QStandardItemModel mymodel
.
mymodel->setColumnCount(3);

. 3

QListView *myview = new QListView(this);


. QListView myview
for(int i = 0 ; i < 6 ;i++)
{
for(int j = 0 ; j < mymodel->columnCount() ; j++ ) {
mymodel->setItem( i , j

,new QStandardItem( QString(member %0,%1).arg(i).arg(j) ));
}
}

. 3 6
1

3
member 0,2

member 0,0

member 0,1

member 1,0

member 1,1

member 1,2

member 2,0

member 2,1

member 2,2

4
5

member 3,0

member 3,1

member 3,2

member 4,0

member 4,1

member 4,2

member 5,0

member 5,1

member 5,2

Model/View Programming

142

;)mymodel->appendRow(itemlist
itemlist
itemlist
.itemlist
4

append 4

member 0,2

member 0,1

member 0,0

member 1,2

member 1,1

member 1,0

member 2,2

member 2,1

member 2,0

member 3,2

member 3,1

member 3,0

member 4,2

member 4,1

member 4,0

4
5

member 5,2

member 5,1

member 5,0

append 3

append 2

append 1

;)QTableView *myview = new QTableView(this


myview QTableView .
.

;)myview->setGeometry(0,0,500,300

;)myview->setModel(mymodel
mymodel myview .
;QModelIndex myindex
myindex QModelIndex .
;)myindex = mymodel->index(2,2
myindex 2 2 . mymodel
;)mymodel->setData(myindex,modified
myindex .modified
Model/View Programming

143

#include widget.h
#include widget.h
#include ui_widget.h
#include <QStandardItemModel>
#include <QTreeView>
#include <QStandardItem>
#include <QModelIndex>
#include <QDebug>

widget.cpp : :
EX
Am
NO ple
31

Widget::Widget(QWidget *parent) :QWidget(parent),ui(new Ui::Widget)


{
ui->setupUi(this);
QList<QStandardItem*> itemlist;
itemlist << new QStandardItem(append 1);
itemlist << new QStandardItem(append 2);
itemlist << new QStandardItem(append 3);
itemlist << new QStandardItem(append 4);
QStandardItemModel *mymodel = new QStandardItemModel;
mymodel->setColumnCount(2);
QModelIndex myindex ;
for(int i = 0 ; i < 3 ;i++){
QStandardItem *item = new QStandardItem( QString(item %0).arg(i) ) ;
mymodel->setItem(i,item);
item->setColumnCount(2);
item->insertRow(0,new QStandardItem);
for(int j = 0 ; j < item->columnCount() ;j++){
myindex = mymodel->index(0,j,item->index());
mymodel->setData(myindex,QString(item %0,%1).arg(i).arg(j) );
}
}
mymodel->appendRow(itemlist);
QTreeView *myview = new QTreeView(this);
myview->setGeometry(0,0,500,300);
myview->setModel(mymodel);
}
Model/View Programming

144

QList<QStandardItem*> itemlist;
itemlist << new QStandardItem(append
itemlist << new QStandardItem(append
itemlist << new QStandardItem(append
itemlist << new QStandardItem(append


1);
2);
3);
4);
.QStandardItem

QStandardItemModel *mymodel = new QStandardItemModel;


QStandardItemModel mymodel
.
mymodel->setColumnCount(2);

2
1

QModelIndex myindex;
. QModelIndex myindex
for(int i = 0 ; i < 3 ;i++){
QStandardItem *item = new QStandardItem( QString(item %0).arg(i) ) ;
. QStandardItem item
mymodel->setItem(i,item);

.i item

item 0

145

Model/View Programming

item->setColumnCount(2);
item->insertRow(0,new QStandardItem);

.item 2
.item

for(int j = 0 ; j < item->columnCount() ; j++ ){


myindex = mymodel->index(0,j,item->index());
.item j 0 myindex
mymodel->setData(myindex,QString(item %0,%1).arg(i).arg(j) );
.myindex
}

1
item 0
item 0,0

2
item 0,1

}
:
2

1
item 0
item 0,0

item 0,1

item 1
item 1,0

item 1,1

item 2
item 2,0

item 2,1

Model/View Programming

146

;)mymodel->appendRow(itemlist
itemlist
itemlist
.itemlist
4

append 4

append 3

item 0,1

item 0
item 0,0

item 1,1

item 1
item 1,0

item 2,1

item 2
item 2,0

append 2

append 1

;)QTreeView *myview = new QTreeView(this


myview QTreeView .
.

;)myview->setGeometry(0,0,500,300

;)myview->setModel(mymodel
mymodel myview .

................................................................................

Model/View Programming

147

/

QAbstractItemDelegate QStyledItemDelegate
.QtDemo
Notes

...........................................................................................................................................................................................................
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
.......................................................................................................................................................................................................... .

148

Model/View Programming


Graphics View
Framework

149

Graphics View Framework

Graphics View Framework

150

: Graphics View Framework


2D

/ ( ) Model / View


.
:
( : ) QGraphicsScene Class
.

( : ) QGraphicsView Class
.

( : ) QGraphicsItem Class
.QGraphicsScene

scene

View

Scene QGraphicsScene
Item QGraphicsItem
View QGraphicsView
scene View
View .Scene
151 Graphics View Framework

:
QObject

QGraphicsScene Class

:


:


.

- ( ) .

. ( : ) Declaration

;QGraphicsScene scene

:


addLine addRect .addEllipse
addItem

QGraphicsItem .Scene
( item( x , y

( ) x , y .Scene
................................................................................

152

Graphics View Framework

QGraphicsView Class

:
QAbstractScrollArea

QAbstractScrollArea QFrame

QFrame QWidget

:


Scene
QGraphicsView
.
( : ) Declaration

;QGraphicsView view

:
setScene

.


.
................................................................................

Graphics View Framework

153

QGraphicsItem Class

:
.QGraphicsScene

( : ) Declaration

;QGraphicsItem item

:


Scene .
QGraphicsItem

:
QGraphicsLineItem : QGraphicsItem . QGraphicsRectItem : QGraphicsItem . QGraphicsTextItem : QGraphicsItem .
.
QGraphicsItem
.

.
................................................................................
154

Graphics View Framework

Qt Creator

. QWidget
.widget.cpp
EX
widget.cpp
Am
#include widget.h
#include ui_widget.h
#include <QtGui>

Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
QGraphicsScene *scene = new QGraphicsScene(0,0,2000,2000,this);
scene->addRect(QRectF(0, 0, 100, 100));
scene->addRect(QRectF(1800, 1800, 100, 100));
QGraphicsView *view1 = new QGraphicsView(scene,this);
view1->setGeometry(0,0,250,250);
view1->setSceneRect(0,0,200,200);
QGraphicsView *view2 = new QGraphicsView(scene,this);
view2->setGeometry(251,0,250,250);
view2->setSceneRect(1800,1800,200,200);
QGraphicsView *view3 = new QGraphicsView(scene,this);
view3->setGeometry(502,0,250,250);

QGraphicsItem *item = scene->itemAt(50, 50);


item->rotate(10);

155

Graphics View Framework

NO ple
32

;)QGraphicsScene *scene = new QGraphicsScene(0,0,2000,2000,this


scene QGraphicsScene
2000 2000.
;))scene->addRect(QRectF(0, 0, 100, 100
( ) 0 0 100 100.
;))scene->addRect(QRectF(1800, 1800, 100, 100
( ) 1800 1800 100 100.
QGraphicsView
:
)(0,0

) ( 2000 , 0
) ( 100 , 100

) ( 1800 , 1800

) ( 2000 , 2000

156

Graphics View Framework

Scene

) ( 0 , 2000

;)QGraphicsView *view1 = new QGraphicsView(scene,this


view1 QGraphicsView .scene
;) view1->setGeometry( 0 , 0 , 250 , 250
( view1 250 250 )
( ) 0 0 .widget
;) view1->setSceneRect( 0 , 0 , 200 , 200
( ) 0 0 200
200.
view1 .
)(0,0

) ( 250 , 0

( 0, 0) in scene

( 100 , 100 ) in scene

view1
) ( 250 , 250

) ( 0 , 250

Graphics View Framework

157

;)QGraphicsView *view2 = new QGraphicsView(scene,this


view2 QGraphicsView .scene
;) view2->setGeometry( 251 , 0 , 250 , 250
( view2 250 250 )
( ) 251 0 widget .view1
;) view2->setSceneRect( 1800 , 1800 , 200 , 200
( ) 1800 1800 200
200.

) ( 251, 0

) ( 501, 0

( 1800, 1800) in scene

( 1900, 1900) in scene

view2
) ( 501, 250

158

Graphics View Framework

) ( 251, 250

;)QGraphicsView *view3 = new QGraphicsView(scene,this


view3 QGraphicsView .scene
;) view3->setGeometry( 502 , 0 , 250 , 250
( view3 250 250 )
( ) 502 0 widget .view2
view3
( ) 2000 7 2000 ( ) 250 7 250
.
;) QGraphicsItem *item = scene->itemAt( 50 , 50
item QGraphicsItem
( ) 50 50 .
10 .view1

)(0,0

) ( 250 , 0

) ( 250 , 250

;) item->rotate( 10

view1

) ( 0 , 250
Graphics View Framework

159

scene :
)(0,0

) ( 2000 , 0
) ( 100 , 100

) ( 1800 , 1800

) ( 2000 , 2000

160

Graphics View Framework

Scene

) ( 0 , 2000


Animation GUI
Framework

Animation GUI Framework

161

162

Animation GUI Framework

: Animation GUI Framework





( ... ) Buttons , Text Box.
:
- 1 ( . ) QObject
- 2 ( .) Q_PROPERTY
- 3 keyframe .
: :

.
:

.


QObject
QAnimation Classes
QAbstractAnimation

QAnimationGroup
QSequentialAnimationGroup

QVariantAnimation
QPropertyAnimation

QParallelAinmationGroup

:
: QPropertyAnimation .
: QSequentialAnimationGroup .
: QParallelAnimationGroup .
163 Animation GUI Framework

. ) 0 0 ( B2 , B1 QPushButton :
:
) 150 150 ( ) 0 0 ( B1 . 5 ) 0 0 (
) 250 250 ( ) 0 0 ( B2 . 3
. B2 , B1 QWidget Qt Creator

.widget.cpp
widget.cpp
EX
A

Widget::Widget(QWidget *parent) :QWidget(parent),ui(new Ui::Widget)


{
ui->setupUi(this);
QPushButton *B1 = new QPushButton(Button B1,this);
QPushButton *B2 = new QPushButton(Button B2,this);

m
NO ple
33

QPropertyAnimation *B_anim1 = new QPropertyAnimation(B1, geometry);


B_anim1->setDuration(5000);
B_anim1->setKeyValueAt(0, QRect(0, 0, 150, 30));
B_anim1->setKeyValueAt(0.8, QRect(150, 150, 200, 60));
B_anim1->setKeyValueAt(1, QRect(0, 0, 150, 30));
QPropertyAnimation *B_anim2 = new QPropertyAnimation(B2, geometry);
B_anim2->setDuration(3000);
B_anim2->setStartValue(QRect(0, 0, 150, 30));
B_anim2->setEndValue(QRect(250, 250, 200, 60));

QSequentialAnimationGroup *S_group = new QSequentialAnimationGroup;


S_group->addAnimation(B_anim1);
S_group->addAnimation(B_anim2);
S_group->start();
Animation GUI Framework

164

;)QPushButton *B1 = new QPushButton(Button B1,this


;)QPushButton *B2 = new QPushButton(Button B2,this
B2 , B1 QPushButton .widget

;)QPropertyAnimation *B_anim1 = new QPropertyAnimation(B1, geometry


B_anim1 QPropertyAnimation
B1 geometry .B1
;)B_anim1->setDuration(5000
.setDuration
5000 5.
( & setKeyValueAt ( qreal real, const QVariant
QVariant geometry .B1
real 1 0 0 1 .
;)) B_anim1->setKeyValueAt( 0 , QRect( 0 , 0 , 150 , 30
B1 ( ) 0 0 150 30.
- 0 = ) 0 7 5000 ( : 0 = 1000 / ( ).30

)(0,0
Button B1
150

B1 ( 0 )

Animation GUI Framework

165

;)) B_anim1->setKeyValueAt( 0.8 , QRect( 150 , 150 , 200 , 60


B1 ( ) 150 150 200 60 .
-- 4000 = ) 0.8 7 5000 ( : 4 = 1000 /.

) ( 150 , 150
60

Button B1
200

B1 4

;)) B_anim1->setKeyValueAt( 1 , QRect( 0 , 0 , 150 , 30


B1 ( ) 0 0 150 30
-- 5000 = ) 1 7 5000 ( : 5 = 1000 / ( )

30

)(0,0
Button B1
150

B1 ( 5 )

166

Animation GUI Framework

;)QPropertyAnimation *B_anim2 = new QPropertyAnimation(B2, geometry


B_anim2 QPropertyAnimation
B2 geometry .B2
;)B_anim2->setDuration(3000

3.

;))B_anim2->setStartValue(QRect(0, 0, 150, 30
B1 ( ) 0 0 150 30 .
30

)(0,0
Button B2
150

B2

;))B_anim2->setEndValue(QRect(250, 250, 200, 60


B1 ( ) 250 250 200 60 .

) ( 250 , 250
60

Button B2
200

B2
Animation GUI Framework

167

;QSequentialAnimationGroup *S_group = new QSequentialAnimationGroup


S_group QSequentialAnimationGroup
.
;)S_group->addAnimation(B_anim1
B_anim1 .S_group
;)S_group->addAnimation(B_anim2
B_anim2 .S_group
;)(S_group->start

.
B1 5 B2 3.



B2 B1 2.

;QSequentialAnimationGroup *S_group = new QSequentialAnimationGroup

;QParallelAnimationGroup *S_group = new QParallelAnimationGroup

................................................................................

168

Animation GUI Framework

QtNetwrok Module

QtNetwork Module

169

>#include <QtNetwork

QT += network
. project.pro

170

QtNetwork Module




.


:
: QHostAddress
.IP Address

: QHostInfo
:

( ) IP Address ( ) HostName
( ) HostName ( .) IP Address
: QTcpSocket
Servers

.TCP/IP
: QTcpServer
Clients

.TCP/IP
: QUdpSocket
.UDP/IP


.
QtNetwork Module

171

QHostAddress Class

:



:
IP Address

:

.IPv6 , IPv4
IP .

:
setAddress
;)setAddress (127.0.0.1

;)setAddress (34322342334

toIPv4Address .
;)QHostAddress myip(192.168.1.1
;)(qDebug() << myip.toIPv4Address
// this print 3232235777
toString .
;)QHostAddress myip(3232235777
;)(qDebug() << myip.toString
// this print 192.168.1.1
................................................................................

172

QtNetwork Module

QHostInfo Class

:



:
:

( ) IP Address ( ) HostName
( ) HostName ( .) IP Address
:
( ) HostName
:
: - lookupHost :
qt.nokia.com
QHostInfo::lookupHost(qt.nokia.com,

;)))this, SLOT(printResults(QHostInfo
.4.2.2.1
QHostInfo::lookupHost(4.2.2.1,
;)))this, SLOT(printResults(QHostInfo
( ) Signals and Slots
.
: - fromName :
qt.nokia.com
;)QHostInfo info = QHostInfo::fromName(qt.nokia.com


.Console
QtNetwork Module

173

QHostInfo , QHostAddress :
QWidget Qt Creator

.widget.cpp , widget.h
widget.h

#include <QWidget>
#include <QtNetwork> <---------
...
class Widget : public QWidget
{
...
public Q_SLOTS: <---------
void printResults(QHostInfo info); <---------
};

EX
Am
NO ple
34

widget.cpp

#include <QtNetwork>
Widget::Widget(QWidget *parent) :QWidget(parent),ui(new Ui::Widget)
{
ui->setupUi(this);
QHostAddress ip;
ip.setAddress(192.168.1.1);
qDebug() << ip.toString();
qDebug() << ip.toIPv4Address();
QHostInfo::lookupHost(www.yahoo.com,
this, SLOT(printResults(QHostInfo)));
QHostInfo::lookupHost(69.147.125.65,
this, SLOT(printResults(QHostInfo)));

}
void Widget::printResults(QHostInfo info)
{
foreach (QHostAddress addr , info.addresses())
qDebug() << addr.toString();
qDebug() << info.hostName();
}

QtNetwork Module

174

;QHostAddress ip

ip .QHostAddress

;)ip.setAddress(192.168.1.1
ip 192.168.1.1 ip.
ip .
192.168.1.1 :
ip .
3232235777 :

;)(qDebug() << ip.toString

;)(qDebug() << ip.toIPv4Address

QHostInfo::lookupHost(www.youtube.com,
;)))this, SLOT(printResults(QHostInfo
lookupHost ( ) IP Addresses
www.youtube.com printResults
.
QHostInfo::lookupHost(209.85.225.136,
;)))this, SLOT(printResults(QHostInfo
lookupHost ( ) Host Name 209.85.225.136
printResults .

................................................................................

QtNetwork Module

175


:

.Transmission Control Protocol - TCP -1
.User Datagram Protocol - UDP -2
: : TCP

TCP Server

TCP Client

Server Client



.
.HTTP , FTP
.QTcpServer , QTcpSocket
: : UDP

UDP Receiver

UDP Sender

UDP Sender

()Broadcasting Sender
( 512 ) ,
UDP Receiver ,
,
UDP .TCP
.QUdpSocket
176

QtNetwork Module

QTcpServer Class

:
QObject


:
Clients

.TCP/IP


Client

Server
IP
Listen
Port

Client Request
connecting to
Server by IP
and Port

IP

connectToHost

Port

incomingConnection(int socketDescriptor)
- create QTcpSocket.
- set QTcpSocket desctiptor.
- set QTcpsocket in an internal list
of pending connections.
- emit newConnection().

177

QtNetwork Module

QTcpServer
Diagram

listen Port , IP

client . server
client server IP
Port :
- 1 socket descriptor
.
- 2 socket descriptor incomingConnection
.
- 3 incomingConnection :
QTcpSocket . socket descriptor. .nextPendingConnection .newConnection :
: listen
newConnection

.
: nextPendingConnection
QTcpServer
:
incomingConnection
3
.
178

QtNetwork Module

Server

. Client
widget QtCreator
. server_message
Network Module
.server_message.pro ) QT+= network (
: widget.ui
QListView Class

ObjectName:
clientlv

QLineEdit Class

ObjectName:
messagldt

179

QtNetwork Module

QTextEdit Class

ObjectName:
logstextedit

QPushButton Class

ObjectName:
sendbtn

#ifndef WIDGET_H
#define WIDGET_H

widget.h

EX
Am
NO ple
35

#include <QWidget>
#include <QtNetwork>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
QTcpServer *server;
QMap<QTcpSocket*,QString> users;
public Q_SLOTS:
void login();
void logout();
void on_sendbtn_clicked();
void updatelist();
private:
Ui::Widget *ui;
};
#endif // WIDGET_H

QtNetwork Module

180

>#include <QtNetwork

QtNetwork .

;QTcpServer *server

server .QTcpServer

;QMap<QTcpSocket*,QString> users
users QMap :
QTcpSocket ( ) Key QString ( ) Value
client QString
( ) connection .QTcpSocket

.client

;)(void login

;)(void logout


.client

;)(void on_sendbtn_clicked


.sendbtn

.server

;)(void updatelist

................................................................................

QtNetwork Module

181

#include widget.h
#include ui_widget.h
#include <QtNetwork>
#include <QStringListModel>

widget.cpp

Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
server = new QTcpServer(this);
server->listen(QHostAddress::Any , 4444);
}

connect(server,SIGNAL(newConnection()) , this , SLOT(login()));

Widget::~Widget()
{
delete ui;
}
void Widget::login()
{
QTcpSocket *newsocket = (QTcpSocket*) server->nextPendingConnection();
int socketnum = newsocket->socketDescriptor();
QString socketstr;
socketstr.setNum(socketnum);
users.insert(newsocket , user_+socketstr);
ui->logstextedit->append(users.value(newsocket)+Logged In);
connect(newsocket, SIGNAL(disconnected()), this, SLOT(logout()));
updatelist();
}
void Widget::logout()
QtNetwork Module

182

QTcpSocket *closesocket = (QTcpSocket*)sender();


ui->logstextedit->append(users.value(closesocket)+Logged Out);
users.remove(closesocket);
updatelist();

void Widget::updatelist()
{
QStringList userlist;
foreach(QString username , users.values())
userlist << username;
QStringListModel *usermodel = new QStringListModel;
usermodel->setStringList(userlist);
ui->clientlv->setModel(usermodel);
}
void Widget::on_sendbtn_clicked()
{
foreach(QTcpSocket *user, users.keys())
user->write((ui->messageldt->text()+\n).toUtf8());
}

#include <QtNetwork>
#include <QStringListModel>
QtNetwork
.QStringListModel
server = new QTcpServer(this);
QTcpServer server
.this widget

183

QtNetwork Module

;)server->listen(QHostAddress::Any , 4444
server socket
( ) IP : localhost ( . ) Port : 4444
;)))(connect(server,SIGNAL(newConnection()) , this , SLOT(login
newConnection server
login this widget
Client server
login .
.............................................................................................

login

;)(QTcpSocket *newsocket = (QTcpSocket*) server->nextPendingConnection


newsocket ( ) connection
nextPendingConnection .newsocket
;)(int socketnum = newsocket->socketDescriptor
socketDescriptor newsocket
.socketnum

;QString socketstr
;)socketstr.setNum(socketnum

;)users.insert(newsocket , user_+socketstr
users :
newsocket ( ) key user_+socketstr ( .) vlaue
;)ui->logstextedit->append(users.value(newsocket)+Logged In
logstextedit .

184

QtNetwork Module

;)))(connect(newsocket, SIGNAL(disconnected()), this, SLOT(logout


disconnected newsocket
logout this widget
Client
logout .
.
.............................................................................................

;)(updatelist

logout

;)(QTcpSocket *closesocket = (QTcpSocket*) sender


logout disconnected client
.
() sender .closesocket
;)ui->logstextedit->append(users.value(closesocket)+Logged Out
logstextedit .
.users

;)users.remove(closesocket

.
.............................................................................................

;)(updatelist

.updatelist

;QStringList userlist
userlist .server
))(foreach(QString username , users.values
;userlist << username
users .userlist
QtNetwork Module

185

;QStringListModel *usermodel = new QStringListModel


mymodel QStringListModel
.
.usermodel

;)usermodel->setStringList(userlist

;)ui->clientlv->setModel(usermodel
usermodel clientlv .
.............................................................................................

.on_sendbtn_clicked

))(foreach(QTcpSocket *user, users.keys


;))(user->write((ui->messageldt->text()+\n).toUtf8
write messageldt .users
:
\n .
.utf8
.
.............................................................................................

186

QtNetwork Module

QTcpSocket Class

:
QAbstractSocket

QIODevice

QObject


:
Servers

.TCP/IP
) Transmission Contol Protocol ) - TCP
:
. - . - Client

Server
IP
Listen
Port

Client Request
connecting to
Server by IP
and Port

IP

connectToHost

Port

Not Succeed
emit error()

HostLookupState
Succeed
emit hostFound()

Not Succeed
emit error()

QTcpSocket
Diagram
187

QtNetwork Module

ConnectingState
Succeed
emit connected()

ConnectedState

client server TCP


:
.IP Address .Port Numbaer :
(): connectToHost .HostLookupState
: ConnectingState
() hostFound.
: ConnectedState
() connected.
: () error () stateChanged.
() state :
() : state .UnconnectedState
client server
().write() , read
() readyRead
.
................................................................................

188

QtNetwork Module

Client

. server
widget QtCreator
. client_message
Network Module
.client_message.pro ) QT+= network (
: widget.ui

QPushButton Class

ObjectName:
connectbtn

QTextEdit Class

ObjectName:
messagebox

QLabel Class

ObjectName:
statuslbl

189

QtNetwork Module

#ifndef WIDGET_H
#define WIDGET_H

widget.h

EX
Am
NO ple
36

#include <QWidget>
#include <QtNetwork>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
QTcpSocket *client;
public Q_SLOTS:
void on_connectbtn_clicked();
void readmessage();
void setconnected();
private:
Ui::Widget *ui;
};
#endif // WIDGET_H

QtNetwork Module

190


QtNetwork .
server . QTcpServer

.connectbtn

>#include <QtNetwork
;QTcpSocket *client

;)(void on_connectbtn_clicked

;)(void readmessage


readyRead .

;)(void setconnected


connected .

.............................................................................................

QtNetwork Module

191

#include widget.h
#include ui_widget.h
#include <QtNetwork>

widget.cpp

Widget::Widget(QWidget *parent) :QWidget(parent),ui(new Ui::Widget)


{
ui->setupUi(this);
client = new QTcpSocket(this);
connect(client, SIGNAL(readyRead()), this, SLOT(readmessage()));
connect(client, SIGNAL(connected()), this, SLOT(setconnected()));
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_connectbtn_clicked()
{
client->connectToHost(localhost, 4444);
}
void Widget::readmessage()
{
while(client->canReadLine())
{
QString line = QString::fromUtf8(client->readLine()).trimmed();
ui->messagebox->append(Message : + line);
}
}
void Widget::setconnected()
{
ui->statuslbl->setText(Connected);
}
QtNetwork Module

192


QtNetwork .

>#include <QtNetwork

;)client = new QTcpSocket(this


client QTcpSocket
widget .this
;)))(connect(client, SIGNAL(readyRead()), this, SLOT(readmessage
readyRead client
readmessage this widget
client
readyRead readmessage .
;)))(connect(client, SIGNAL(connected()), this, SLOT(setconnected
connected client
setconnected this widget
connected
setconnected .
.............................................................................................

.on_connectbtn_clicked

;)client->connectToHost(localhost, 4444
client server localhost
( ) Port . 4444
.............................................................................................

QtNetwork Module

193

readmessage

))(while(client->canReadLine
{

;)(QString line = QString::fromUtf8(client->readLine()).trimmed

;)ui->messagebox->append(Message : + line
}
canReadLine true
readLine client
messagebox .append

UTF8 QString::fromUtf8

server Utf8 .
.............................................................................................

.setconnected

;)ui->statuslbl->setText(Connected
setText Connected statuslbl .
.............................................................................................

194

QtNetwork Module

QUdpSocket Class

:
QAbstractSocket

QIODevice

QObject

:
UDP

UDP
( ) Audio ,Video Chat
.
UDP
( ) Port number
UDP Receiver UDP Sender
.

UDP Receiver
on Port 4444
UDP Receiver
on Port 4444
UDP Sender
on Port 4444

UDP Receiver
on Port 4444

UDP Receiver
on Port 4444

QtNetwork Module

195

:

: UDP .4444 - : UDP .4444

.............................................................................................

:
QtCreator widget
. udp_sender
Network Module
( ) QT+= network .udp_sender.pro
widget.ui:

QLabel Class

QLineEdit Class

ObjectName:
messageldt

196

QtNetwork Module

widget.h

#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QtNetwork>

EX
Am
NO ple
37

namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
public Q_SLOTS:
void senddata();
private:
Ui::Widget *ui;
QUdpSocket *udpsender;
};
#endif // WIDGET_H

#include <QtNetwork>
QUdpSocket *udpsender;


. QtNetwork
.QUdpSocket udpsender

void senddata();


. textChanged

197

QtNetwork Module

#include widget.h
#include ui_widget.h

widget.cpp

#include <QtNetwork>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
udpsender = new QUdpSocket(this);
connect(ui->messageldt, SIGNAL(textChanged(QString)), this, SLOT(senddata()));
}
Widget::~Widget()
{
delete ui;
}
void Widget::senddata()
{
QString str = ui->messageldt->text();
QByteArray datagram;
datagram.append(str);
udpsender->writeDatagram(datagram.data(), datagram.size(), QHostAddress::Broadcast, 4444);
}

QtNetwork Module

198


QtNetwork .

>#include <QtNetwork

;)udpsender = new QUdpSocket(this


udpsender QUdpSocket
widget .this
;)))(connect(ui->messageldt, SIGNAL(textChanged(QString)), this, SLOT(senddata
textChanged messageldt
senddata this widget
messageldt textChanged
senddata .
.............................................................................................

.senddata

;)(QString str = ui->messageldt->text


str .messageldt

datagram .

;QByteArray datagram
;)datagram.append(str

str .datagram

udpsender->writeDatagram(datagram.data(), datagram.size(),

;)QHostAddress::Broadcast, 4444
() datagram.data ()datagram.size
QHostAddress::Broadcast
.4444
QtNetwork Module

199

:
QtCreator widget
. udp_receiver
Network Module
( ) QT+= network .udp_receiver.pro
widget.ui:

QLabel Class

QLabel Class

ObjectName:
messagelbl

200

QtNetwork Module

widget.h

#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QtNetwork>

EX
Am
NO ple
38

namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
public Q_SLOTS:
void readdata();
private:
Ui::Widget *ui;
QUdpSocket *udpreceiver;
};
#endif // WIDGET_H

#include <QtNetwork>
QUdpSocket *udpreceiver;


. QtNetwork
. QUdpSocket udpreceiver

void readdata();


. readyRead

201

QtNetwork Module

#include widget.h
#include ui_widget.h
#include <QtNetwork>

widget.cpp

Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
udpreceiver = new QUdpSocket(this);
udpreceiver->bind(4444, QUdpSocket::ShareAddress);
}

connect(udpreceiver, SIGNAL(readyRead()),this, SLOT(readdata()));

Widget::~Widget()
{
delete ui;
}
void Widget::readdata()
{
while (udpreceiver->hasPendingDatagrams()) {
QByteArray datagram;
datagram.resize(udpreceiver->pendingDatagramSize());
udpreceiver->readDatagram(datagram.data(), datagram.size());
ui->messagelbl->setText(datagram.data());
}
}

QtNetwork Module

202


QtNetwork .

>#include <QtNetwork

;)udpsender = new QUdpSocket(this


udpreceiver QUdpSocket
widget .this
;)udpreceiver->bind(4444, QUdpSocket::ShareAddress
bind udpreceiver 4444
QUdpSocket::ShareAddress .
;)))(connect(udpreceiver, SIGNAL(readyRead()),this, SLOT(readdata
readyRead udpreceiver
readdata .this widget
4444 readyRead
readdata .
.............................................................................................

.readdata

datagram .

;QByteArray datagram

;))(datagram.resize(udpreceiver->pendingDatagramSize
datagram .
;))(udpreceiver->readDatagram(datagram.data(), datagram.size
() datagram.data ().datagram.size
;))(ui->messagelbl->setText(datagram.data
messagelbl .

................................................................................

QtNetwork Module

203

Notes

...........................................................................................................................................................................................................
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
........................................................................................................................................................................................................... .
.......................................................................................................................................................................................................... .
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................
............................................................................................................................................................................................................

204

QtNetwork Module

QtSql Module

QtSql Module

205

>#include <QtSql

QT += sql
. project.pro

206

QtSql Module




:
: QSqlDatabase
SQL Database Drivers
QSqlDatabase :
DataBase Type

IBM DB2
Borland InterBase
MySQL
Oracle Call Interface
) Open Database ( Microsoft
PostgreSQL
SQLite v2.0
SQLite v3.0
Sybase Adaptive server

Qt Driver Name
QDB2
QIBASE
QMYSQL
QOCI
QODBC
QPSQL
QSQLITE2
QSQLITE
QTDS

: QSqlQuery
SQL

( ) SELECT , INSERT .

: QSqlField
.

: QSqlError
.

................................................................................
QtSql Module

207


QSqlDatabase

:
: addDatabase . : setHostName ( .) Database Server : setDatabaseName . : setUserName . : setPassword . : open .;)QSqlDatabase db = QSqlDatabase::addDatabase(QMYSQL
;)db.setHostName(dbhost
;)db.setDatabaseName(dbname
;)db.setUserName(myuser
;)db.setPassword(mypass
;)(db.open
SQL
QSqlQuery . exec
;QSqlQuery query
;) ) query.exec(INSERT INTO userpoints VALUES( 'Mahmoud' , 2000
bind prepare :
prepare . SQL bind . exec . .SQL
208

QtSql Module

: SQL
:varname, :varpoints prepare :
.:varname, :varpoints bind
query.prepare(INSERT INTO userpoints (name, points)
VALUES (:varname, :varpoints));
query.bindValue(:varname, Ali);
query.bindValue(:varpoints, 500);
query.exec();
:varname, :varpoints prepare :
. bind
query.prepare(INSERT INTO userpoints (name, points)
VALUES (:varname, :varpoints));
query.bindValue( 0 , Ali);
query.bindValue( 1 , 500);
query.exec();
prepare :
. bind
query.prepare(INSERT INTO userpoints (name, points)
VALUES ( ? , ? ));
query.bindValue( 0 , Ali);
query.bindValue( 1 , 500);
query.exec();
209

QtSql Module

: prepare
bind .
)query.prepare(INSERT INTO userpoints (name, points
;)) ? VALUES ( ? ,
;) query.addBindValue( Ali
;) query.addBindValue( 500
;)(query.exec
..................................
:
SELECT ( SQL

) :
: .

()next () : previous . : .

()first : .

()last ( : seek(int num .num ( ) Record
( ) Fields
(.value( field num
: SQL
name .id
.users
;)QSqlQuery query(SELECT id , name FROM users
{ ) )(while ( query.next

;)(int id = query.value( 0 ).toInt

;)(QString name = query.value( 1 ).toString
}
210

QtSql Module

:


QSqlQueryModel QSqlTableModel
/
( ) Model / View Framework
.QtGui Module
..................................
:




:
3 3.
Points

Name

NO

2000

Mahmoud

500

Ali

1200

Mohsen

QSQLITE
.Database host

QtSql Module

211

SQL
:
)CREATE TABLE userpoints(id int , name varchar(20) , points int
)INSERT INTO userpoints VALUES( 1 , Mohamed , 2000
)INSERT INTO userpoints VALUES( 2 , Ali , 500
)INSERT INTO userpoints VALUES( 3 , Mohsen , 1200

.QtSQL Module
QtCreator widget
. sql_module

( ) QT+= sql .sql_module.pro
widget.ui:
QTableView Class

ObjectName:
datatable

212

QtSql Module

QWidget Class

#include widget.h
#include ui_widget.h
#include <QtSql>
#include <QStandardItemModel>
#include <QTableView>

widget.cpp

Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
QSqlDatabase db = QSqlDatabase::addDatabase(QSQLITE);
db.setDatabaseName(:memory:);
db.open();
QSqlQuery query;
query.exec(create table userpoints (id int primary key,
name varchar(20), points int));
query.exec(INSERT INTO userpoints VALUES(1, Mahmoud, 2000));
query.prepare(INSERT INTO userpoints (id, name, points)
VALUES (:id, :name, :points));
query.bindValue(0, 2);
query.bindValue(1, Ali);
query.bindValue(2, 500);
query.exec();
query.prepare(INSERT INTO userpoints (id, name, points)
VALUES (:id, :name, :points));
query.bindValue(:id, 3);
query.bindValue(:name, Mohsen);
query.bindValue(:points, 1200);
query.exec();

213

QtSql Module

EX
Am
NO ple
39

int rows = 0;
QStandardItemModel *mymodel = new QStandardItemModel;
mymodel->setColumnCount(3);
query.exec(SELECT * FROM userpoints);
while (query.next())
{
mymodel->setItem(rows , 0 ,new QStandardItem( query.value(0).toString() ));
mymodel->setItem(rows , 1 ,new QStandardItem( query.value(1).toString() ));
mymodel->setItem(rows , 2 ,new QStandardItem( query.value(2).toString() ));
rows++;
}
ui->datatable->setModel(mymodel);
}

#include <QtSql>


. QtSql

QSqlDatabase db = QSqlDatabase::addDatabase(QSQLITE);
QSqlDatabase db
.QSQLite
db.setDatabaseName(:memory:);
db :memory:
QSQLite :memory:
.
db.open();

. db

QtSql Module

214

QSqlQuery query;
query.exec(create table userpoints (id int primary key,
name varchar(20), points int));
query.exec(INSERT INTO userpoints VALUES(1, Mahmoud, 2000));
.exec SQL
query.prepare(INSERT INTO userpoints (id, name, points)
VALUES (:id, :name, :points));
. :id, :name, :points prepare SQL
query.bindValue(0, 2);
query.bindValue(1, Ali);
query.bindValue(2, 500);
query.exec();

:
:id 0
:name 1
:points 2

query.prepare(INSERT INTO userpoints (id, name, points)


VALUES (:id, :name, :points));
query.bindValue(:id, 3);
query.bindValue(:name, Mohsen);
query.bindValue(:points, 1200);
query.exec();
:id, :name, :points prepare SQL
. bind

215

QtSql Module

int rows = 0;

. int rows

QStandardItemModel *mymodel = new QStandardItemModel;


mymodel->setColumnCount(3);
.
query.exec(SELECT * FROM userpoints);
.userpoints SQL
while (query.next())
{
mymodel->setItem(rows , 0 ,new QStandardItem( query.value(0).toString() ));
mymodel->setItem(rows , 1 ,new QStandardItem( query.value(1).toString() ));
mymodel->setItem(rows , 2 ,new QStandardItem( query.value(2).toString() ));
rows++;
}
ui->datatable->setModel(mymodel);
while query.next :
.datatable mymodel
query.value toString
QVariant value
.toString , toInt , toDouble QVariant
points
.int value
int pointsval = query.value(2).toInt();

................................................................................

QtSql Module

216

Multithreaded Programmig
)QThread Class(

217

Multithreaded Programming

Multithreaded Programming

218

Multithreaded Programming


.


..


.



( )
.
QThread

.
................................................................................

Multithreaded Programming

219

QThread Class

:
QObject


:


.
:
() : run .
() : start ().run () : started ().run () : finished ().run () : terminated ().run :
:
.QThread () run ( )public . () run . ().start () start () started
() run () finished
().terminated
.
220

Multithreaded Programming

: .

main :
Thread

Thread

isRunning
False

isRunning
True


thread

................................................................................
Thread :
Thread

=5

Thread

!= 5

5 Thread
Thread False
.
:
: main.cpp .main
:mythread.h .QThread
:mythread.cpp .QThread
Multithreaded Programming

221

mythread.h

#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
class mythread : public QThread
{
Q_OBJECT
public:
explicit mythread(QObject *parent = 0);
void setTestVal(int);
void run();
private:
int testval;
};
#endif // MYTHREAD_H
#include mythread.h
#include <QDebug>

EX
Am
NO ple
40

mythread.cpp

mythread::mythread(QObject *parent) :
QThread(parent)
{
testval = 0;
}
void mythread::setTestVal(int i)
{
this->testval = i;
msleep(10);
}
void mythread::run()
{
while(testval !=5);
qDebug() << The thread finished\n;
this->testval = 0;
}
Multithreaded Programming

222

mythread.h
mythread .QThread

class mythread : public QThread


Q_OBJECT

Q_Object .QObject
testval .private

;)void setTestVal(int
;)(void run

() run .
main
() run main mythread
() start .main.cpp

................................................................................
mythread.cpp

)(void mythread::run
{
;)while(testval !=5
;qDebug() << The thread finished\n
;this->testval = 0
}
() run while testval
5 testval The thread finished
0 testval ().finished
:
( ;( ) while( testval !=5
main main.cpp
() run QThread .main
Multithreaded Programming

223

main.cpp

#include <QtCore/QCoreApplication>
#include <QTextStream>
#include <QDebug>
#include mythread.h
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
mythread tr;
tr.start();
QTextStream in(stdin);
QString val;
QObject::connect( &tr , SIGNAL(finished()) , &a , SLOT(quit()));
while(tr.isRunning())
{
qDebug() << The Thread Still Alive\n;
qDebug() << Set the Value to close the thread :;
in >> val;
tr.setTestVal(val.toInt());
}
return a.exec();
}

mythread tr;
tr.start();

.mythread tr
.mythread run)( start)(

QTextStream in(stdin);
.stdin QTextStream in
QString val;

.QString val
Multithreaded Programming

224

;)))(QObject::connect( &tr , SIGNAL(finished()) , &a , SLOT(quit


() finished mythread
() quit QCoreApplication

mythread ()finished
QCoreApplication () quit .
))(while(tr.isRunning
{
;qDebug() << The Thread Still Alive\n
;qDebug() << Set the Value to close the thread :
;in >> val
;) )(tr.setTestVal( val.toInt
}
while isRunning
True () run mythread
isRunning False
() run mythread
in >> val .val
() setTestVal testval private
.mythread
:

5 :
testval .mythread
() run ().finished
isRunning False .
() finished QCoreApplication
() quit .

................................................................................

Multithreaded Programming

225

Foundation of Qt Development C++ GUI Programming with Qt 4 (2nd Edition( C++ GUI Qt 4 Qt 4 Professional programming with C++ -

qt.nokia.com www.qtforum.org -

:
ahbanna@gmail.com

226

227

( ) 1

Memory Managment
( ) The Heap ( .) The Stack
The Heap Memory
: .
: ( ) Pointer .heap

;]int *p[100
: Heap new .delete
;]char *string = new char[100
<----- Heap
...
delete string; <----- Heap

delete
Heap .Stack

The Stack Memory


: .
: ( ) Pointer .stack

;]int p[100
: stack ( } )
( { )
{
;]int p[100
<----- Stack
...
}
<----- Stack



( )parent Stack Heap
( ) .
228

) 2 (
++
C++ Classes Structure
.) C++ Classes KeyWord ( ++
class - new - delete - public - private - protected - friend
:
(

::

->

class myclass : inherites class

)
.) Class Standard Structure (

{
myclass() <--- Constructor Function
~myclass() <--- Destructor Function
public: <---
private: <---
protected: <---
};
myclass :: myclass() <--- Constructor Function
{
}
myclass :: ~myclass() <--- Destructor Function
{
}

229

( ) 2
++
C++ Classes Structure
Pointer .
new .myclass

;myclass *ptr
;ptr = new myclass

delete .
( < ) -
.Heap

;delete ptr

;ptr->class_object

( ) .
.Stack
................................................................................

230

;myclass ptr
;ptr.class_object

( ) 3

Mac OS X

: xcode_iphone_sdk.dmg apple.com

: Qt4.7.dmg qt.nokia.com

231

( ) 3
:
/Developer/Application/Qt .
:
Assistant.
Designer.
Linguist.
:
Qt Creator.

:
/Developer/Examples/Qt .

:

/Developer/Application/Qt/qtdemo.

232

( ) 3

Windows

qt.nokia.com .

233

( ) 3

C:\Qt\2010.05\qt\bin.

Assistant.
Designer.
Linguist.

:
Qt Creator.

Qt Creeator
C:\Qt\2010.05\bin.

234

( ) 4

QtCreator

Qt Creator

- New File or Project File

- ( )

:
Qt Gui Application

:
Qt Console Application

235

) 5 (

ClasName

Inherits

Macros , Constructors and Destructors


Level
NON

Variables
Level

Type
Macro

Q_OBJECT

Type

Function member

Name

Info

Setters and Getter Function members


Level

Setters Functions
Type
Function

Level

Getters Functions
Type
Function

Level

Q_SIGNALS
Type
Function

Slots and Signals


Level

Q_SLOTS
Type

Function

236

) 5 (

ClasName

Inherits

Macros , Constructors and Destructors


Level
NON

Variables
Level

Type
Macro

Q_OBJECT

Type

Function member

Name

Info

Setters and Getter Function members


Level

Setters Functions
Type
Function

Level

Getters Functions
Type
Function

Level

Q_SIGNALS
Type
Function

Slots and Signals


Level

237

Q_SLOTS
Type

Function

) 5 (

ClasName

Inherits

Macros , Constructors and Destructors


Level
NON

Variables
Level

Type
Macro

Q_OBJECT

Type

Function member

Name

Info

Setters and Getter Function members


Level

Setters Functions
Type
Function

Level

Getters Functions
Type
Function

Level

Q_SIGNALS
Type
Function

Slots and Signals


Level

Q_SLOTS
Type

Function

238

) 5 (

ClasName

Inherits

Macros , Constructors and Destructors


Level
NON

Variables
Level

Type
Macro

Q_OBJECT

Type

Function member

Name

Info

Setters and Getter Function members


Level

Setters Functions
Type
Function

Level

Getters Functions
Type
Function

Level

Q_SIGNALS
Type
Function

Slots and Signals


Level

239

Q_SLOTS
Type

Function

( ) 114 :

240

*

*

*

You might also like