Вы находитесь на странице: 1из 929

C++

Windows, Mac OS X Linux


, ,
-, , , ,
, XML, QML JavaScript
230

HawwwMv.ru

5.3

C++

-
-
2015
004.438++
32.973.26-018.1
68

.
68 Qt 5.3. C++. .:

-, 2015. 928 .: . ( )
ISBN 978-5-9775-3346-1
Windows, Mac OS X Linux
Qt 5.3. ,
, ,
. Qt Creator
Qt Quick.
Qt 5, ,
-
. .

004.438++
32.973.26-018.1

:

.
.




05.03.15.
701001/16. . . . . 74,82.
1 500 .
"-", 191036, -, ., 20.
""
199034, -, 9 , 12/28

ISBN 978-5-9775-3346-1 2015


, "-", 2015

20
22
23
23

32

I. QT 43
1. Qt 45
Qt 45
Qt 46
Qt 48
QtCore 48
QtGui 49
QtWidgets 49
QtQuick QtQML 50
QtNetwork 51
QtXml QtXmlPatterns 51
QtSql 51
QtOpenGL 51
QtWebK.it QtWebKitWidgets 51
QtMultimedia QtMultimediaWidgets 51
QtScript QtScriptTools 51
QtSvg 52
52

2. 53
55
58
60
61
4

66
67
68
70
71

3. Qt 72
72
Qt Assistant 72
qmake 72
Qt 76
77
RCC 78
Qt- 79
79
GDB (GNU Debugger) 80
83
Qt 86
Qt 87
89

4. 90
91
92
Java 93
STL 94
foreach 96
96
QVector<T> 97
QByteArray 98
QBitArray 99
QList<T> QLinkedList<T> 99
QStack<> 101
QQueue< > 101
102
QMap<K,T> QMultiMap<K,T> 103
QHash<K, > QMultiHash<K, > 104
QSet<T> 105
107
108
109
109
109
110
111
QVariant 113
114
115
5

II. 117

5. ? 119
QWidget 119
122
123
123
124
127
127
128
130

6. 131
(layout managers) 131
133
QBoxLayout 133
QHBoxLayout 135
QVBoxLayout 136
137
QGridLayout 138
144
QSplitter 144
145

7. 146
146
150
153
155

8. , 156
? QAbstractButton 156
156
156
157
157
160
161
162
165

9. 166
QAbstractSlider 166
166
166
167
167
6

1 67
169
170
172

10. 173
173
175
178
(syntax highlighting) 178
? 184
185
1 86
187
188

11. 189
189
189
191
191
191
192
193
196
196
198
199
200
201

12. , - 202
203
203
205
206
208
210
210
214
215
(Proxy model) 222
- 224
226

13. 227
230
7

III. 231
14. 233
235
235
QKeyEvent 235
QFocusEvent 238
. QPaintEvent 238
239
QMouseEvent 239
QWheelEvent 243
enterEvent() leaveEvent() 243
. QTimerEvent 243
(drag & drop) 244
QDragEnterEvent 244
QDragLeaveEvent 244
QDragMoveEvent 244
QDropEvent 244
244
QChildEvent 244
QCloseEvent 244
QHideEvent 245
QMoveEvent 245
QShowEvent 245
QResizeEvent 245
246
event() 247
250
25 1

15. 252
252
255

16. 256
259

IV. 261
17. 263
263
263
264
266
266
267
267
QColor 267
RGB 268
8

HSV 269
CMYK 270
271
272
273

18. 274
QPainter 275
277
277
278
279
(Anti-aliasing) 280
281
28 1
282
283
283
286
286
287
288
288
288
288
(painter path) 289
290
(composition mode) 291
294
296

19. 297
297
BMP 297
GIF 298
PNG 298
JPEG 298
298
- 300
Qlmage 300
Qlmage 307
- 308
QPixmap 308
QPixmapCache 310
QBitmap 310
QPixmap 310
31 1
314
9

20. 316
318
321

21. 322
324
324
325
327
333
335

22. 336
QMovie 336
SVG- 338
339
342
346
349

23. OpenGL 350


OpenGL 350
Qt OpenGL 352
OpenGL- 352
OpenGL- 355
OpenGL 356
359
363

24. 364
QPrinter 364
369

25. 370
370
375

26. 376
378
382
383
383
384
384
QStyle 388
388
389
390
391
392
396
10

27. 397
397
WAV-: QSound 398
:
QMediaPlayer 399
QMediaPlayer 406
408

V. 409
28. 411
418
420

29. 421
421
422
drag 424
drop 426
428
433

30. 435
435
lupdate 437
Qt Linguist 438
lrelease. , 439
441
443
444

31. 445
445
449
450
451

32. 452
452
QDialog 453
453
454
454
458
458
460
461
462
463
11

464
465
466
468
469
469
470
About Qt 470
471
471

33. 473
473
475
(Online Help) 476
478

34. , SDI- MDT- 480


QMainWindow 480
QAction 481
482
484
485
487
SDI- MDI- 489
SDI- 489
MDI- 493
501

35. (Desktop) 502


502
507
5 11
511

VI. QT 513
36. , / 515
/. QlODevice 515
. QFile 517
QBuffer 518
QTemporaryF 519
. QDir 519
520
. QFilelnfo 523
? 523
524
524
524
524
12

525
/ 527
QTextStream 527
QDataStream 529
529

37. , 531
531
QDate 531
QTime 533
QDateTime 534
534
535
QTimer 537
QBasicTimer 539
539

38. 540
540
543
545
545
- 546
55 1
554
554
556
556
557
QtConcurrent 557
559

39. 561
561
- 562
- 563
- 568
UDP- UDP- 572
576
583
585
586

40. XML 587


XML- 587
XML Qt 589
DOM 589
XML- 590
XML- 592
13

SAX 594
XML- 594
QXmlStreamReader XML 597
XQuery 599
602

41. 603
SQL 603
604
604
604
605
605
SQL Qt 605
( ) 607
SQL ( ) 608
SQL- ( ) 611
612
613
615
616

42. 617
617
618
(plug-ins) 621
Qt 621
623
627
629

43. Qt API 630


Windows API 632
Linux 635
Mac OS X 635
639
641

44. Qt Designer. 642


Qt Designer 642
645
(layout) 646
647
648
650
650
652
653
655
14

45. 657
658
661
663
664
665

46. WebKit 666


667
? 668
668
Web- 670
670
670
671
Web-, 671
676

47. Qt Creator 677


678
Hello Qt Creator 679
Qt Creator 684
685
685
685
688
? 688
688
689
689
694
694
694
694
695
, 695
696
696
697
698
699
699
699
Step Over 700
Step Into 701
Step Out 701
701
(Local and Watches) 702
(Call Stack) 703
703
15

48. Qt 4 Qt 5 705
Qt 5 Qt 4 705
Qt 5 705
706
706
qFindChildren<T*>() 707
707
WebKit 707
707
Plug-ins 707
QPrinter 708
708
708
Qt 5 Qt 4 708
71 1

VII. QT SCRIPT 713


49. 715
716
719
, 720
721

50. 723
723
724
724
725
725
725
726
726
726
728
728
728
728
729
730
73 1
732
732
if... else 732
switch 733
733
734
break continue 734
16

for 734
while 734
do...while 735
with 735
735
try...catch 736
throw 736
737
738
739
741
742
744
744
745

51. Qt Script 746


Global 746
Number 746
Boolean 746
String 747
747
747
747
747
RegExp 747
748
748
Array 748
749
749
749
750
750
750
750
Date 751
Math 752
752
753
753
753
753
754
754
754
Function 755
755
17

52. Qt Script 756


QScriptValue 756
QScriptContext 756
QScriptEngine 757
759
760
, 767
Qt Script 770
773

VIII. QT QUICK 775


53. Qt Quick 777
? 777
QML 779
779
JavaScript QML 783
784

54. 786
786
788
790
792
794
797
799

55. 800
800
807
811

56. 812
812
813
Image 813
Borderlmage 816
817
818
819
821

57. 822
822
825
829
830
832
834
18

58. 835
835
837
838
839
840
842
845
845
848
851

59. / 852
852
852
XML- 853
855
Flickable 855
ListView 856
GridView 858
PathView 860
863

60. Qt Quick C++ 864


QML C++ 864
C++ QML 865
877

878

879
1. ASCII 881

2. 884
3. 887
4. 891
901

,
,

(Goes)

.

Let's start with a fictional story. Imagine ten years ago, someone came to me and asked: Is it
possible to write a feature-rich graphical application, and then compile and run this application
natively on all different major operating systems? On Linux, on UNIX, on Windows, and on the
Macintosh? Back then as a young computer scientist I would probably have answered,
No, that's not possible. And if it was, the system would be very difficult to use, and limited by the
weakest platform. Better choose one platform, or write your code several times.
A few years later I discovered Qt and how wrong I was!
Qt makes true cross-platform programming a reality, without limiting your choices and creativity.
It gives users what users want: fast, native applications that look and feel just right. It gives
developers what developers want: a framework that lets us write less code, and create more.
A framework that makes programming fun again, no matter whether we do commercial work or
contribute to Open Source projects.
Too good to be true? You don't believe me? Well, the proof is easy. I'll pass the word on to Max,
who will tell you exactly how it's done. Max, your turn.
Before I leave, let me wish you good luck with your first Qt-steps. But be careful, it may very well
turn into a lifetime addiction. Either way, I hope you will have as much fun using Qt as we have
creating it for you.
Matthias Ettrich
October 1st, 2004, Oslo

. , 10 -
:
,
? Linux, UNIX, Windows, Macintosh?
, , , : , .
,
.
.
Qt , !
21

Qt ,
. Qt ,
: , . Qt
, : ,
, .
, ,
(Open Source).
, ? ? ,
. , , . ,
.
, Qt.
, Qt . ,
, Qt,
.

1 2004,



,
. , (Ulrich W. Eise-
necker), .
: ,
, .

-, ,
, ,
.
(Matthias Ettrich) Nokia
KDE ,
. (Kent Hansen) (Andreas
Aardal Hanssen) , Nokia
, .
, ,
: , , ,
, , , , ,
, , , , -
, , , , ,
. . , , ,
, , , ,
, , , , ,
, , ,
.


...

, ,
, Qt, .
... ,
Qt.
,
.
, Qt,
Qt, .
, , ,
, .
, , Qt
, ,
.
, . ,
Phonon , , Phonon
Qt 5. QtMultimedia.
.
, , , ,
Qt 5
,
.

. , , Qt.


. ,
Qt 4,
48, Qt 5 Qt 4
.
24

I. Qt

Qt.
1. Qt
1 , Qt,
, Qt.

2.
2 ,
, .
3. Qt
,
make-, .

4.
4 ,
.
. Qt
, .
,
. , , - .
, QString
, .
QVariant,
.

II.
,
. .

5. ?
5 .
, ,
, , . ,
.
QStackedwidget,
.

6.
(Layouts),
,
QSplitter. .

7.
7 ,
.
25

, .
.

8. ,
8
: , .
.
.

9.
9 ,
: , , .

10.
10 ,
. :
, , .
QValidator
.

11.
11 , , , ,
.

12. , -
- ,
.

13.
13 ,
.

III.

Qt.

14.
14 ,
: .
, , .
, .

15.
15 ,
. ,
QObject, , ,
, ,
26

,
.

16.
16 ,
, , .

IV.
,
.
.

17.
1 7 , , ,
. .

18.
, , .

(),
QPicture, ,
.

19.
19 QPixmap
Qimage.
.
.

20.
.

21.
21 QGraphicsScene,
. ,
,
, .

22.
QMovie,
GIF- MNG-.

23. OpenGL
23 OpenGL Qt ,
OpenGL
. Qt, OpenGL.
27

OpenGL: ,
, , .

24.
24 , :
,
.

25.
25 ,
. , ,
.

26.
,
(Look & Feel). ,
,
CSS (Cascading Style Sheets) .

27.
,
QtMultimedia.

V.

.

28.
28
.
, ,
, ,
.

29.
29
(drag & drop).

30.

. 30 ,
.

31.
. 31
: , , ,
, ,
.
28

32.
32 .
, , . ,

.

33.
.
33 .

34. , SDI- MDI-



,
QMainWindow.
SDI (Single Document Interface),
MD1 (Multiple Document Interface).

35. (Desktop)
35
.
( Windows
) .
QSystemTrayicon, .
, QDesktopwidget,
.

VI. Qt
Qt,
,
,
, , -
.

36. , /
36 , Qt ,
.
,
().

37. ,
,
,
.

38.
38 ,
, . -
29

, .
(mutex) , , .
39.
39 , TCP/UDP-,
. : QFtp,
FTP; QHttp,
HTTP;
QNetworkAccessManager.

40. XML
,
XML (extensible Markup Language).
XML-.
DOM (Document Object Model) ,
DOM- XML-.
SAX (Simple API for XML) XML-.

41.
41 .
. QSqlQuery
SQL- (Structured Query Language), , .
,
.

42.
,
.
. , (plug
ins).

43. Qt API
43 Windows Linux
, Qt.

44. Qt Designer.
44, Qt Designer,
, .

45.
. 45
, Qt
.

46. WebKit
46 QtwebKit,
WWW (World Wide Web),
30

Web. , Web-
Web-.

47. Qt Creator
47 , ,
.
, .

48. Qt 4 Qt 5
48 , Qt 5,
Qt 5. ,
Qt 4.

VII. Qt Script
Qt Script,
Script 4.0 , JavaScript 2.0 JScript.NET.

.

49.
Qt Script Qt-
,
.

50.
50
: , , , ,
, .

51. Qt Script
Qt Script . Object, Math, String,
Boolean, RegExp, Number, Date np.

52. Qt Script
52 ,
C++ ,
, ,
.

VIII. Qt Quick
Qt Quick,
QML .

53. Qt Quick
, Qt Quick,
, .
, Qt Quick.
31

54.
,
.

55.
55 Qt
(layout) ,
QML. ,
.

56.

, , .

57.
5 7 ,
,
.

58.
, , , . .
, ,
.

59. /
59 ,
.

60. Qt Quick C++


, C++, QML
( Qt Quick) .

. 1 ASCII-,
2 , 3 ,
4 .


FTP-
- fftp://ftp.bhv.ru/9785977533461.zip
www.bhv.ru (. 4).

,
. Software ( ) GUI (Graphical User Interface,
) .
Windows API (Application Programming Interface,
)
,
. ,
Windows, , , MFC,
, . -
.
, , .
Windows, , ,
- ? ,
, .
.
. ,
Mac OS X ,
Android, , Windows?
,
(). :
,
, , ,
, .


, .
, ,
XCode Mac OS X.
, , , . .
,
.
33

Qt , C++,
Windows,
Linux Mac OS X. Qt . Qt
: Microsoft Windows, Mac OS X, Linux, Solaris,
AIX, Irix, NetBSD, OpenBSD, HP-UX, FreeBSD UNIX XI 1,
iOS, Android, Windows Phone, Windows RT BlackBerry.
, Qt Embedded Qt
(Embedded Systems). Qt API
, ,
, .
,
, Qt
, .
, ,
. ,
,
-
.
C++
,
.
Qt
Qt Designer, .

Qt Quick, Qt.
Qt , .
, , .
Qt , : Adobe, Amazon, AMD, Bosch, Blackberry,
Cannon, Cisco Systems, Disney, Intel, IBM, Panasonic, Pioneer, Philips, Oracle, HP, Goober,
Google, NASA, NEC, Neonway, Nokia, Samsung, Siemens, Sony, Xerox, Xilinx, Yamaha .
, , , ,
Qt. , ,
:
KDE Software Compilation 4 (www.kde.org), Linux
FreeBSD (. .1);
Autodesk Maya (www.autodesk.com) (. .2);
Linux- - Skype (www.skype.com) Microsoft,
VoIP (Voice Over IP),
(. .);
Adobe Photoshop Album (www.adobe.com)
(. .4);
Google Earth (earth.google.com),
200 (. .5);
VirtualBox (www.virtualbox.org)
Sun Microsystems (. .6);
34

. .1. KDE Software Compilation 4 ( www.wikipedia.org)

. .2. 30- Autodesk Maya ( www.wikipedia.org)


35

rs Skype
MAX SCHL
ii Add Credit
(c\ Search

|Q Contacts
allnaschlee
CURRENT CALLS On hold c? %
al
,- aj
RECENT
Hi Neonway
S-} Mark

History

allnaschlee C

E H X E

Hello

. B.3. Skype

!> Mein Katalog - Adobe Photoshop Album Starter Edition 3.0 -


Keine
X

Datei Bearbeiten Ansicht Suchen Hilfe M

QQ - gBestellen - Fotcbereich Ordnen :j Kalenderansicht


IS| . , . m.
--
1) 1
t


Sammlungen Tags


!937
Neu... 3 f V
Neue Elemente: ImportiertvonFestplatteam... Alles einblenden ? Vollbild presentation

fcla
21.7.1997 21.7.1997
047 Am Abend J... 048DIE-1 JPG

ik Adobe-
**
**.
Photoshop Album
I M *T
Starter Edition .
21.7.1997 21.7.1997 16.7.1997 16.7.1997
052 Es wird wie i... 054 Der Seehafen... 002 Am Lifer Rus... 003 Wladiwostok

vl.O
Asiish Aganrai SumitAwasth tuagehdra Bangaiore Mabeep S.8h*sa. Kran ChararaZ. SapnaCharyar Pan> Gaft, Ar.isj
Dhwran Mo'iGupD MiAu Gupta. !#3<3 has. SechiBJafr tiarsar ... Khar Amt Kumar. Sismits Kimtu
Ahr. Li. tfoha Ms. Dsep'ka Marcs Srrr'f Mafera Yvorr.s Murray. Jagannadi Rao. Sreeaha Rsrganathar. Atetaya
Ssxsri. Arv'rs Stairs Lslrraj Sfcarma Motw Snarma. Rams" Sharma. Wok Kumar Singh ' R. Singh. Krishna Singh.
Ravi Singh 3hfipTng, OebiV'irai- AsakoYoshimura

IMS Adobe Syrsrs A Rghts Reserved. Adobe, the Adobe ago. and Photoshop are either reg'stered
tracer-arks c- tracer-arks of Adobe Systems -corporate: in the L r tes States and'or other countries

1 i#2 Elemente gefi dun* LSJitarte 5.737595 5.781,785 5,819801


- 5929866 5543,063 5.995,086 6,026.583 6204.856 6,411.730
6363509.Wertae Patents argemskisL F\V
Adobe

. B.4. Adobe Photoshop Album


36

. .5. Google Earth

VLC media player (www.videolan.org/vlc/),


0.9 (. .7);
Parallels (www.parallels.com)
Parallels (. .8);
Kindle (. . 9) Amazon (www.amazon.com),
, , ,
Kindle-Shop;
Bitcoin (www.bitcoin.org) (. . 10)
Litecoin (www.litecoin.org).
Qt, .
Qt 40
, , ,
- , Apple Store, Google Play , Amazon Appstore
BlackBerry World. Qt-:
TraderStar (www.neonway.com/traderstar),
(. .1 1);
HappyBirthday (www.neonway.com/happy),
,
(. . 12);
ChordsMaestro (. .13) 7
(www.neonway.com/apps/chordsmaestro);
37

InnoTek VirtualBox
_

. .6. VirtualBox ( www.virtualbox.org)

-
. big_buck_byrry_1080p_stert<xog9 VLC media piayei
Media Audio video Playback Playlet Tools Help

ea i m
btg_biickJ>unriy..lQ80p,sterco,ogg 04:54/07 KJO

. B.7. VLC media player


38

. .8. Parallels

Search

OS X Lion Apps


Money
Online
eBay. YAHOO!,

U - -
Now

MCI5ILE TREASURE
WirxJows 8 Apps ISLAND
wrtft HTML, CiS BUSI NESS

m
tnd lvScript
"
1

__

. B.9. Amazon Kindle


39

"=]

. , , .

[ ] 14uqCFH6YnPTA2GWvi9i8D447cYy66MAne
[ ] U8D4476YnPTAzGWvi9i8DzGWvYy6zGWve
[ ] 14uqCFH6Yni8D447viCFH6447cYy66MAne
[ ] CFH6CFH6YnPTAzGWvi9iCFH67cYyi8D447

,
|
0,-0
-#i

. .10. Bitcoin

. .11. TraderStaroT Neonway


40

Happy Birthday (max.schlee@neonwaY.com)

I fc. | ( : -4 11
Olga AgaPonova 54
Mukesh Ahir 85
Wkwong Alan 9 Neonway
Nataly Alexandrova 54
:
Robert Alumbaugh 222
Roshan Arnendra 362
Victor Aner 54 info@neonway.com
Nader Aprahamian 300
Monu Bane 347 : +49 631-147440
Stephen Barnes 101
Craig Bartle 297
Dieter Bauermeister 252
Franz Beischl 160
Krishna Bhattarai 241
Olaf Boehm 324
Luise Boettcher 323
Allan Bonney 47 :
Robert Borchers 277
Julia Braun 111
LeiP Buren 152 ()
Timothy Bush 182
Erii Ca 30
Hari Cahyono 195
Igor Canck. 54
A1

. .12. HappyBirthday Neonway

. .13. ChordsMaestro iPad Neonway


41

. .14. FLEXXITY DigitalFilmTechnology Weiterstadt

FLEXXITY (www.dft-film.com/archive/flexxity_archive.php)
DigitalFilmTechnology Weiterstadt, ,
(. .14);
ChatCube Goober Networks, Inc. ,
(. .15).

. .15. ChatCube Goober Networks, Inc.


42

, Qt
. Qt
, :
- (,
OpenGL);
,
;
XML (extensible Markup Language);
STL- ;
/;
;
, Oracle, Microsoft SQL Server, IBM
DB2, MySQL, SQLite, Sybase, PostgreSQL;
.
Qt - .
, , ,
.
, , . .
(plug-ins) ,
.
, .
, Qt
C++, , . ,

: Qt# #, PerlQt Perl, PyQt Python, . .
, Qt, Qt Script.


.
Qt , QtAsisstant
.
, , Qt
(Open Source), ,
.
, Qt :
+ + .

Qt 5!

, 20 2014 .
Qt

, ,
, .

1. Qt
2.
3. Qt
4.
1

Qt

Qt
, , ,
, .
Hello, World (, ),
. 1.1.

.
, .
,
. , ,
.

. 1.1.
Hello, World

1.1. Hello, World. hello.cpp

iinclude <QtWidgets>
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QLabel lbl ("Hello, World !");
.
lbl show ( ) ;
return app . exec ( ) ;
}

1.1 Qtwidgets,

: QApplication QLabel. ,
46 I. Qt

Qtwidgets,
QApplication QLabel, ,
, . ,
,
(Precompiled Headers),
, .
. QApplication,
.
.
,
, ,
, . Qt
,
, .
QLabel. Qt
, show().
QLabel ,
. ,
,
.
,
.
,
QApplication::(). ,
QCoreApplication, QGuiApplication,
QApplication.
. ,
QCoreApplication::exit (),
. QApplication::()
, , .

Qt
, , -
, , .
Qt , ,
.
Qt ( 500),
,
, , , .
. Qt ,
(. 1.1).
Qt-
1.1 : Qtcore, QtGui Qtwidgets,

make- (. 3) . -
1. Qt 47

1.1. Qt

, ,
QtCore core


QtGui gui

, QtGui
QtWidgets widgets
C++
,
Qt Quick quick

, QML
QtQML qml
JavaScript
QtNetwork network

QtOpenGL opengl OpenGL


QtSql sql
SVG (Scalable Vector
QtSvg svg
Graphics, )
XML, ,
QtXml xml
SAX DOM

QtXmlPatterns
XPath, XQuery, XSLT
xmlpatterns
XmlShemaValidator
QtScript script

QtScriptTools scripttools .

QtMultimedia multimedia
QtMultimediaWidgets multimediawidgets QtMultimedia
QtWebKit webkit Web-
QtWebKitWidgets webkitwidgets QtWebKit
QPrintSupport print support

,
QtTest test

(. 3). ,
, :
QT += widgets opengl network sql

:
QT -= gui

. I.I QtCore,
. ,
QtCore, : QtNetwork, QtGui, QtSql Qtxml. , , ,
: QtOpenGL QtSvg.
48 I. Qt

Qt ,
.
. , Qtwidgets
, 1.1:
# include <QtWidgets>

Qt
Qt ,
. -
, Qt (, red,
Qt : : red). - Qt,
:
using namespace Qt;

QtCore
, QtCore.
, .
, , ,
. QtCore 200 ,
:
: QList, QVector, QMap, QVariant, QString . . (. 4);
: QiODevice, QTextStream, QFile (. 36);
QProcess : QThread,
QWaitCondition, QMutex (. 55);
: QBasicTimer QTimer (. 37);
: QDate QTime (. 37);
QObject, Qt (. 2);
QEvent (. 14);
QSettings (. 28);
QCoreApplication, , ,
;
: QAbstractAnimation, QVariantAnimation . . (. 22);
: QStateMachine, QState . . (. 22);
: QAbstractltemModel, QStringListModel, QAbstractProxyModel
(. 12).
(. 5).
QCoreApplication.
QCoreApplication , ,
. QCoreApplication
,
1. Qt 49

. QCoreApplication
. :
;
.
, QCoreApplication , ,
,
.
Singleton.

QtGui
, OpenGL OpenGL
ES. QWindow,
, ,
.
QGuiApplication.
:
(. 29);
,
(. 13);
.

QtWidgets
,
.
300 . :
Qwidget Qt.
, ,

. 254 53 . 5
;
: QVBoxLayout, QHBoxLayout (. 6);
: QLabel, QLCDNumber (. 7);
: QPushButton, QCheckBox, QRadioButton (. 8);
: QSlider, QScrollBar (. 9);
: QLineEdit, QSpinBox (. 10);
: QComboBox, QTooiBox(. 11);
: QMainwindow QMenu (. 31 34);
: QMessageBox, QDiaiog (. 32);
: QPainter, QBrush, QPen, QColor (. 18);
: Qimage, QPixmap (. 19);
50 I. Qt

(. 26) ,
, ;
QApplication, .

QApplication,
. ,
QCo1ication, ,
. QApplication
Qt-, .
, , ,
. ,

, .
QApplication QGuiApplication
:
.
(Look & Feel) , (. 26)\
(desktop);
(,
)
;

(. 28).
, ,
. QApplication
alert ( ) . -
Mac OS X (. 1.2) Windows (. 1 .3).

. 1.2.
- Mac OS X

QtQuick QtQML
,

QML, JavaScript Qt
(. 53).
1. Qt 51

QtNetwork
QtNetwork TCP-
UDP- ( QTcpSocket QudpSocket), -,
HTTP- FTP- ( QNetworkAccessManager).
39.

QtXml QtXmlPatterns
Qtxml XML
SAX2- DOM-, Qt (. 40).
QtXmlPatterns
XML : XPath, XQuery, XSLT XmlShemaValidator.

QtSql
. ,
(. 41).

QtOpenGL
QtOpenGL OpenGL Qt- -
. QGLWidget,
QWidget (. 23).

QtWebKit QtWebKitWidgets
QtwebKit Web.
QtwebKitewidgets
Web
. 46.

QtMultimedia QtMultimediaWidgets
QtMultimedia
. ,
, ,
- .
QtMultimediaWidgets ,
.
27.

QtScript QtScriptTools
QtScript
JavaScript. QtScriptTools
. VII.
52 I. Qt

QtSvg
SVG, XML.

, (. 22).

Qt , :
QtCore, QtGui, QtWidgets, QtQuick, QtQML, QtScript, QtMultimedia, QtWebKit, QtNetwork,
QtOpenGL, Qtsqi, Qtxml QtSvg. ,
, , .
, ,
, .
QtCore,
( ). QCoreApplication
.

QtWidgets QtQuick. QGuiApplication QApplication
Qt- .
.
2

,
, , .

Qt , . ,
QObject , . Qt
. , ,
.


,
QObject ( ) , (Meta Object
Compiler, ) .
. 2.1
.

2.1.

class MyClass : public QObject, public AnotherClass {


, QObject
. ,
, QObject.

QObject :
(signal/slot);
;
;
;
;
;
54 I. Qt

;
.
,
, .
.
, QObject,
. .
37.

,
, -
.
.
, QObject,

(. 15).
,
, ,
.
. Qt
qobject_cast<T> ( ) , ,
(. 3) , QObject.
, .
,
Qt Script (. VII).
Qt Designer (. 44),
Qt .
Q_PROPERTY. :
Q_PROPERTY(type name
READ getFunction
[WRITE setFunction]
[RESET resetFunction]
[DESIGNABLE bool]
[SCRIPTABLE bool]
[STORED bool]
)

, (READ).
.
(WRITE), (RESET), (DESIGNABLE)
() , ,

Qt Designer. (SCRIPTABLE) ,
, Qt Script. ,
(STORED) , ,
.
, , (
),
( 2.2).
2. 55

2.2.

class MyClass : public QObject {


Q_OBJECT
Q_PROPERTY(bool readonly READ isReadOnly WRITE setReadOnly)

private:
bool m_bReadOnly;

public:
MyClass(QObject* pobj = 0) : QObject (pobj )
, m_bReadOnly(false)
{
}

public:
void setReadOnly(bool bReadOnly)
{
m_bReadOnly = bReadOnly;
}

bool isReadOnly () const


{
return m_bReadOnly;

MyClass, 2.2, QObject.


m bReadOnly, .
false.
MyClass isReadOnly () setReadOnly () .
Q PROPERTY. isReadOnly () ,
READ, setReadOnly ( )
,
WRITE.
:
pobj->set Property("readonly", true);

:
bool bReadOnly = pobj->property("readonly").toBool ();



. .
(callback functions),
X Window System, ,
.
, . ,
56 I. Qt

,
void. ,
, .
, . ,
, , , .
,
,
, .
Motif.
, Motif Windows API
, -
.
, , C++,
Windows. (
)
Microsoft Foundation Classes (MFC). -
, ,
- .
-
, (
-), , ,
MFC- . MFC
, Windows, ,
,
- .
, Microsoft Microsoft Word
MFC .
MFC
( 2.3).
, .

2.3. , MFC

class CPhotoStylerApp : public CWinApp {


public:
CPhotoStylerApp();
public:
virtual BOOL Initlnstance();

afx_msg void OnAppAbout();


afx_msg void OnFileNew));

DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(CPhotoStylerApp, CWinApp)
ON_COMMAND(ID_APP_ABOUT, OnAppAbout)
ONJCOMMAND(ID_FILE_NEW, OnFileNew)
ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew)
2. 57

ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen)
ON_COMMAND(ID_FILE_PRINT_SETUP, CWinApp::OnFilePrintSetup)
END_MESSAGE_MAP()

, 2.3,
.

, . ,

. ,
, . -
, , ,
. -,
. -, DoDataExchange {)
DDX_Text ( ) ,
. -,
, UpdateData ( ) true
false.
,
, ,

( ).
, , ,
.
C++. , C++
,
, .
, ,
.
, Qt
. ,
, Qt C++
.
C++ Qt
(Meta Object Compiler, ).
Q OBJECT
. ,
.
C++
,
. ,
,
. Q OBJECT
class .
, .
,
.

, -.
Qt,
58 I. Qt

. QObject
.
.
: , .
:
, .
:
, QObject,
;
, ,
;
.
;
,
;
;
, .
, ,
(. 38);
-
. ,
.
, :
C++,
;
, ,
;
QObject;
:
;
. ,
.
, , Windows, (. 3)
CONFIG console ( Mac OS X Linux
).


-
,
. . .

(signals) : ,
,
,
. . Qt
2. 59

, .

, . ,
, , , ,
. ,
.
, , ,
. , , ,
. ,
,
, .


, ,
, , .

. Qt
- . ,
,
.
, , .
,
.
. - ,
void.
. ,
.
, -
, .

. ,
, .
2.4.

2.4.

class MySignal {
Q_OBJECT

signals:
void dolt();

};

doit ( ) .
, :
void MySignal::doIt()
{
QMetaObject::activate(this, sstaticMetaObject, 0, 0);
60 I. Qt

, private,
protected public, .
emit. ,
, emit doit ( )
doit ( ) . , .
, 2.4 doit()
MySignal, .
, sendsignal ( ) ,
MySignal doit ( ) , 2.5.

2.5.

class MySignal {
Q_OBJECT
public:
void sendSignal()
{
emit dolt();

signals:
void dolt();
};

, .
, ,
, 2.6.

2.6.

class MySignal : public QObject {


Q_OBJECT
public:
void sendSignal()
{
emit sendString("Information");

signals:
void sendString(const QStrings);
};

(slots) , . ,
.
. , public, private protected.
,
, ,
protected private. public.
: private slots:, protected
slots: public slots:. .
2. 61


,
. ,
.

, , .
: slotMethod(int = 8),
static.
.

. 2.7.

2.7.

class MySlot : public QObject {


Q_OBJECT
public:
MySlot ( );
public slots:
void slot ( )
{
qDebugO "I'm a slot";
}
};

sender () ,
. QObject. ,
, :
void slot ()
{
qDebug ( ) sender ( ) ->obj ectName ( );
}


connect ( ) ,
QObject. connect ()
:
QObj ect::connect ( const QObject* sender,
const char* signal,
const QObject* receiver,
const char* slot,
Qt::Connect ionType type = Qt: Autoconnection
);

:
sender , ;
signal , . (
) SIGNAL(method ( ) );
62 I. Qt

receiver , ;
slot , .
SLOT (method ( ) ) ;
type . :
Qt: : Direct Connect ion
, Qt:: QueuedConnection (. 14)
, Qt: Autoconnection
, :
,
Qt:: DirectConnection, Qt::QueuedConnection.
(Qt: Autoconnection) connection () .
, , .
connect ( ) ,
,
, ,
connect (). :
QObj ect::connect ( const QObject* sender,
const QMetaMethods signal,
const QObject* receiver,
const QMetaMethods slot,
Qt::Connect ionType type = Qt: Autoconnection
);


, const char*.
.
, ,
.
,
.
,
connect ( ).
void main ()

QObject::connect (pSender, SIGNAL(signalMethod ( ) ),


pReceiver, SLOT ( slotMethod ( ))
);


connect ( ):
QObj ect::connect (pSender, &SenderClass::signalMethod,
pReceiver, &ReceiverClass::slotMethod

connect ( ) .
2. 63

, QObject, QObject::
:
MyClass::MyClass() : QObject()
{

connect(pSender, SIGNAL(signalMethod()),
pReceiver, SLOT(slotMethod())
>;

, ,
connect ( ) ,
(pReceiver), -. ,
- this, :
MyClass::MyClass() : QObject()
{
connect(pSender, SIGNAL(signalMethod()), SLOT(slot()));
}
void MyClass::slot()
{
qDebugf) "I'm a slot";
}

connect ( ) Connection,
, .
, , , , -
, Q ASSERT () .
Connection bool,
.
.
bool bOk = true;
bOk &= connect(pcmdl, SIGNAL(clicked()), pobjReceiver1, SLOT(slotButtonlClicked()));
bOk &= connect(pcmd2, SIGNAL(clicked()), pobjReceiver2, SLOT(slotButton2Clicked()));
Q_ASSERT(bOk);
, ,
. ,
( emit) .
. :
MyClass MyClass() : QObjectO
{
connect(pSender, SIGNAL(signalMethod()), SIGNAL(mySignal()));
}

, biockSignais( )
true. ,
biockSignais () false. signalsBlockedO
.
64 I. Qt

, . 2.1,
. ( 2.8-2.10),
(. 2.1, ) , (. 2.1, )
. ADD ()
. ,
.

-

Counter 1 10 1 S3 11
0 ADD

. 2.1. -.

2.8. main.cpp

# include <QtWidgets>
# include "Counter. h"

int main (int argc, char** argv)


{
QApplication app(argc, argv);

QLabel lbl ("0") ;


QPushButton cmd ( "ADD" ) ;
Counter counter;

.
lbl show ( ) ;
.
cmd show ( ) ;

QObject: : connect (& cmd, SIGNAL (clicked () ) ,


scounter, SLOT (slot Inc () )
);

QObject: : connect (& counter, SIGNAL (counterChanged (int) ) ,


&lbl, SLOT (setNum( int) )
);

QObject: : connect (& counter, SIGNAL (goodbye ( ) ) ,


&app, SLOT (quit ( ) )
);

.
return app exec ( ) ;
}

( 2.8) lbl,
cmd counter ( 2.9-
2.10). clicked () slotincO.
slotincO, 1.
,
. counterChanged ( int ) ,
, setNum(int),
.
2. 65


, ,
. , , int,
, QString.

!
, int
. ,
. , .

, goodbye ( ) , ,
quit ( ) , ,
ADD . ,
.

2.9. Counter.h

#pragma once

#include <QObject>

// ======================================================================
class Counter : public QObject {
Q_OBJECT
private:
int m_nValue;

public:
Counter();

public slots:
void slotlncO;

signals:
void goodbye ( );
void counterChanged(int);
};

2.9, :
goodbye(), , counterChanged(int),
, slotlncO,
.

2.10. counter.cpp

#include "Counter.h"

//
Counter::Counter() : QObject()
, m_nValue(0)
{
}
,,
66 I. Qt

void Counter::slotlnc()
{
emit counterChanged(++m_nValue);

if (m_nValue == 5) {
emit goodbye();
}
}

2.10 slotlnc () : counterChanged ( )


goodbye(). goodbye( ) m nvalue, 5.
, , , .
, , ,
. :
MyClass::MyClass() : QObjectO
{
connect(pSender, SIGNAL(signalMethod(int)), SIGNAL(mySignal()));
}

, ,
. ,
, .


,
. Qt
,
. disconnect () ,
connect ( ) .
:
QObject::disconnect(sender, signal, receiver, slot);

,
:
void main()
{

QObject::disconnect(pSender, SIGNAL(signalMethod()),
pReceiver, SLOT(slotMethod())
);

, : disconnect(signal, receiver,
slot) disconnect(receiver, slot).
2. 67


-
, QSignalMapper.
,
int, QString QWidget.
QString. , , :
Button 1 Action,

Button2 Action. , ,
, clicked ( )
.
QSignalMapper ( 2.1 1).

2.11.

MyClass::MyClass(QWidget* pwgt)
{

QSignalMapper* psigMapper = new QSignalMapper(this);


connect (psigMapper, SIGNAL(mapped(const QStringS) ),
this, SLOT(slotShowAction(const QString&) )
);

QPushButton* pcmdl = new QPushButton("Buttonl");


connect (pcmdl, SIGNAL(clicked ()), psigMapper, SLOT(map ( ) ) );
psigMapper->setMapping (pcmdl, "Buttonl Action");

QPushButton* pcmd2 = new QPushButton("Button2");


connect (pcmd2, SIGNAL(clicked ( ) ), psigMapper, SLOT(map ( ) ) ) ;
psigMapper->setMapping (pcmdl, "Button2 Action");

}
void MyClass::slotShowAction(const QString& str)
{
qDebug ( ) str;
}

2.11 QSignalMapper mapped ()


slotShowAction () , QString.
QSignalMapper (), ,
. QSignalMapper::
setMappingO ,

, clicked ( ).
, ,
,
.
68 I. Qt



.
QObject :
QObject (QObject* pobj = 0);

QObject
. -
. -.
, , , ,
,
. -
,
setParent ( ) .
. setObjectName
. ,
. ,
objectNameO, 2.12.

2.12.
QObject* pobjl = new QObject;
QObject* pobj 2 = new QObject (pobjl) ;
QObject* pobj4 = new QObject (pobj2) ;
QObject* pobj3 = new QObject (pobjl) ;
pobj2->setObjectName ("the first child of pobjl") ;
pobj3->setObjectName ("the second child of pobjl") ;
pobj4->setObjectName ("the first child of pobj2");

2.12 ( ).
pobj 2
pobjl. pobj 3 pobjl, pobj 4 pobj2.
. 2.2.

( )
- .
,
2. 69

.
, ,
new, .

, C++,
Qt
/
. Qt ,
, new.
, .

: parent ( )
children ( ) . parent ( ) -.
. 2.2, pobj2->parent () objl.
0. -
- , , 2.13 (
pobj4 2.12).

2.13.
for (QObject* pobj = pobj4; pobj; pobj = pobj->parent()) {
qDebug() pobj->objectName();
1

:
the first child of pobj2
the first child of pobjl
children!) -.
(. 2.11, . 2.2), pobjl->chiidren()
QObjectList, : pobj2 pobj3.
- findChiidt).
. ,
pobj4:
QObject* pobj = pobjl->findChild<QObject*>("the first child of pobj2");

findchildreno,
. ,
, (. 4),
, -.
. ,
th, :
QList<QObject*> plist = pobjl->findChildren<QObject*>(QRegExp("th*"));

, ,
:
QList<QObject*> plist = pobjl->findChildren<QObject*>();

pobj2, pobj3
pobj4.
70 I. Qt

dumpObjectinfoO,
, :
;
, ;
- .
stdout.
dumpObjectTreeO,
- . , dumpObjectTreeO
pobj1 2.1 1 :
QOb j ect : :
QObject::the first child of pobjl
QObject::the first child of pobj2
QObject::the second child of pobjl


, QObject ,
, ( QMetaObject).
, ( ),
.
QObject: : metaobject . , , ,
, , :
qDebugO pobj l->metaObj ect () ->className ;
, :
if (pobj l->metaObject ( ) ->className ( ) == "MyClass") {
/ / -

inherits (const
char*), QObject true,

, false. :
if (pobj->inherits ("QWidget") ) {
QWidget* pwgt = static_cast<QWidget*> (pobj ) ;
/ / - c pwgt
}

qobject_cast<T>.
, inherits ( ) :
QWidget* pwgt = qobject_cast<QWidget*> (pobj ) ;
if (pwgt) (
/ / - c pwgt
)

tr(),
. 30.
2. 71

.

,
.
,
. , ,
. , ,
, , .

signals, slots. C++
public, protected, private.
.
emit. , ,
QObject , . -
(), disconnect () ,
,
.
QObject::connect().
QObject ,
Qt. QObject :
, .
,
. QObject
new,
.
,
C++, ,
( ),
-,
.
, ,
Q OBJECT.
3

Qt

, .

Qt ,
,
Qt.


(IDE, Integrated
Development Environment),
Qt-. Microsoft Visual Studio, IBM Eclipse, QDevelop . ,
, Qt Creator (. 3.1). IDE
Qt. , ,
, ,
47.

Qt Assistant
, . ,
.
Qt Assistant, Web-. Qt Assistant
Qt.
,
-docPath. . 3.2 Qt Assistant.
QAssistantciient Qt Assistant
.

qmake

.
make- (makefile),
.
3. Qt 73

. 3.1. Qt Creator

. 3.2. Qt Assistant
74 I. Qt

make-
,
.
, . , make-
, .

, .
qmake Qt, 3.0. ,
, Qt. qmake make-
, pro
. , qmake make-
, -.
, , C++,
:
qmake -project

pro-. ,
-
. ,
, -,

. - make- ,
:
qmake file.pro - Makefile

, file.pro
pro-, a Makefile
make-.


Mac OS X qmake.
make- GNU C++:
qmake -spec macx-g++ - Makefile
XCode:
qmake -spec macx-xcode - Makefile
.

, qmake
pro- , , make-.
, C++,
, :
qmake -project
qmake
make
, -,
. 3.1
pro-,
Qt, (
Qt Assistant).
3. Qt 75

3.1.

HEADERS

SOURCES ( )
FORMS ui.
Qt Designer XML
(. 40 44)
TARGET . ,

LIBS ,

CONFIG ,

DESTDIR ,

DEFINES . ,
debuger

INCLUDEPATH , .
, ,
()
DEPENDPATH ,

SUBDIRS , -

TEMPLATE . : , lib
, subdirs

TRANSLATIONS , (. 31)

. , pro-
:
TEMPLATE =
HEADERS += filel.h \
file2.h
SOURCES += main.cpp \
filel.cpp \
file2.cpp
TARGET = file
CONFIG += qt warn_on release
. ,
TEMPLATE = ( , TEMPLATE
lib). , HEADERS,
, . SOURCES
, TARGET , CONFIG ,
. ,
:
qt , Qt- Qt;
warn on ,
;
76 I. Qt

release ,
, .

Mac OS X CONFIG ,
. , 32- lntel-

86, 64- lntel- 86_64.
, qmake ,
, .
, qmake
make- ,
.
.
,
. pro- Examples. pro
, , FTP-
- ftp://ftp.bhv.ru/9785977533461.zip.
:
TEMPLATE = subdirs
SUBDIRS = Examplel Example2 .... ExampleN


clean,
, make-,
distclean. : make distclean.

!
FTP-
- ftp://ftp.bhv.ru/9785977533461.zip
www.bhv.ru (. 4).

Qt
.
h,
. ,
iifndef.
, ,
.
#ifndef _MyClass_h_
tdefine _MyClass_h_
class MyClass {

};
#endif //_MyClass_h_

,
:
3. Qt 17

#pragma once
class MyClass {

};

, , .
, ,
,
#include.
Q OBJECT , ,
, , .
, -
qobject_cast<T>(obj).
class MyClass : public QObject {
Q_OBJECT
public:
MyClass();

,
. main.cpp.
, ,
, .
.
,
, ,
Qt , .


(, Meta Object Compiler), ,
, , ,
, , C++.
- ,
. - ,
C++. :
moc_<filename>.cpp.

!
moc- #inciude
"main.moc" . , :
#include <QtGui>
int main(int argc, char** argv)
{
QApplication app(argc, argv);

return app.exec();
}
#include "main.moc
78 I. Qt

,
.
, main.cpp.

, ,
. moc-
:
- proc.moc proc.h

proc.moc.
, QObject, ,
QMetaObject.
, - , .

RCC
,
, . .
, -
. , , ,
.
,
.
, .
()
qrc (Qt Resource Collection,
Qt). XML. :
< ! DOCTYPE RCCXRCC version="1. 0">
<qresource>
<file>images/open.png</file>
<file>images/quit .png</file>
</qresource>
</RCC>
( )
open. png quit. png C++,
,
. C++ .
, ,

. qrc- pro- RESOURCES,
qmake . :
RESOURCES = images . qrc

open. png, ,
, :
plbl->setPixmap (QPixmap ( " : /images/open. png" ) ) ;
3. Qt 79

images
. ,
. ,
.
, xml-
<file> alias, :
<!DOCTYPE RCCXRCC version="1.0">
<qresource>
<file alias="open.png">. ./very/long/path/images/open.png</file>
<file alias="quit ,png">. /very/long/path/images/quit.png</file>
</qresource>
</RCC>


:
plbl->setPixmap(QPixmap(":/open.png"));

:
plbl->setPixmap(QPixmap(":/very/long/path/images/open.png"));

,
.

Qt-
Qt- .
, , . Qt
C++
pro. qmake make-. make-
(. 3.3).
make- C++
. qrc-,
C++, . ++-
, link
.


(bug, , , ).
.
, .
, , :
(code review);
, 45.
, , , ,
, ,
, . -
80 I. Qt

file.exe

. 3.3.

,
, ,
, . Qt

, GDB , Microsoft Visual Studio.
,
,

, .
GDB, Windows, Linux, Mac OS X.

GDB (GNU Debugger)


GDB UNIX.
,
,
, : XXGDB, DDD KDBG. ,
IDE,
.
IDE, GDB .
, ,
( 3.1).
3. Qt 81

3.1.

void bug()
{
int n = 3;
int* pn = &n;
// !
delete pn;
}

int main()
{
bug();
return 0;

3.1 main() bug(),


,
delete , .
,
.
-,
, :
g++ - bug.cpp - bug

Qt pro-
. . pro- Qt,
,
pro- CONFIG debug debug_and_release.

, ,
:
gdb bug.exe


, GDB core-,
.
, ,
core-. , Windows
, GDB,
(Windows Linux).

:
(gdb)
, .
run:
(gdb) run
82 I. Qt

,
. , .
where:
(gdb) where

:
#0 0x77f767ce in _libmsvcrt_a_iname ()

#6 0x00401305 in operator delete(void*) ()


#7 0x004012ae in bug() () at bug.cpp:5
#8 0x004012df in main () at bug.cpp:10

, main( ) bug( ) ,
.
up
. , bug ( ) :
(gdb) up 1

:
#7 0004012 in bug() () at bug.cpp:5
5 delete pn;

- ,
print. :
(gdb) print n

:
$1-3

(break points)
break. bug ( ) :
(gdb) break bug
(gdb) run
:
Breakpoint 1, bug() () at bug.cpp:3
3 int n =3;

, next.
:
(gdb) next
4 int* pn = &n;
, .
, ,
step. ,
main () step bug(). . 3.2
.
3. Qt 83

3.2. GDB

quit
help . -
,
run
attach
detach
break .
.
, . ,
< >:< > < >:< >
tbreak break ,

clear .
.
, . ,
: < >:< >
< >:< >
delete
disable
enable
continue .

next .

step .
. next,

until



, .
,
-. Qt
QObject: :dumpObjectinfo(),
.
Qt ,
.
QtGlobal : Q ASSERTO
Q_CHECK_PTR ( ) :
Q ASSERT ( )
, true;
84 I. Qt

,
Q CHECK PTR ( )
0, , ,
.
Qt qDebugO, qWarningO qFatal(),
QtGlobal. print f ().
printf ( ) ,
. Microsoft Visual Studio ,
Linux .

qFatalO
.
,
.
qlnstallMessageHandler ( ) .
, :
void fct (QtMsgType type, const QMessageLogContexts context, const QStrings msg)

fct .
, QtMsgType: QtDebugMsg, QtWarningMsg
Qt FatalMsg. ,
. ( 3.2).

3.2.

void messageToFile (QtMsgType type,


const QMessageLogContexts context,
const QStrings msg

.
QFile file ( "protocol log" ) ;
if ( ! file. open (QIODevice: :WriteOnly | QIODevice: :Text I QIODevice ::Append) )
return;

QTextStream out (sfile) ;


switch (type) {
case QtDebugMsg:
out "Debug: " msg ", context. file endl;
break;
case QtWarningMsg:
out "Warning: " msg ", " context. file endl;
break;
case QtCriticalMsg:
out "Critical: " msg ", " context. file endl;
break;
case QtFatalMsg:
out "Fatal: " msg ", " context. file endl;
abort ( ) ;
3. Qt 85

int main(int argc, char** argv)


{
QApplication app(argc, argv);
qlnstallMessageHandler(messageToFile);

qDebugO, qwarningO qFatal ( )


protocol.log, .
, .
protocol.log
.
.
, QObject::objectName ( ) .
QObject::
dumpobjectinfo ( ) , .

QCoreApplication ,
(. 15).
Qt QDebug.
C++ cout. ,
qDebugO
:
qDebugO "Test";
QDebug,
QtDebugMsg. , , :
QDebug(QtDebugMsg) "Test";
, , ,
.
, qDebugO
.
, ,
dummyOutput( )
qlnstallMessageHandler ( ) , 3.3.

3.3. , qDebugO, cJWaming () qFatal ()

void dummyOutput(QtMsgType, const QMessageLogContexts, const QStrings)


{
}

int main(int argc, char** argv)


{
QApplication app(argc, argv);
#ifndef QT_DEBUG
qlnstallMessageHandler(dummyOutput);
#endif
)
86 I. Qt

qDebugO :
qDebugO "Testl" 123 "Test2" 456;

, , ,
qDebug ( ) , qwarning ( ) qFatal ( ) ,
, .

Qt
Qt QtGlobal ,
.
qMax(a, ) qMin ( , )
:

int n = qMax<int> (3, 5); // = 5


int n = qMin<int>(3, 5); // = 3

qAbs () :
int n = qAbs (-5); // = 5

qRound ( ) :
int n = qRound (5. 2); // = 5
int n = qRound (-5 . 2) ; // = -5

qBound ( ) , :
int n = qBound (2, 12, 7); // =7

. ,
.
qFuzzyCompare ( ) .
double float true,
, false.
,
.
, , .
. ,
, 1,0. :
double dValuel = 0.0;
double dValue2 = myFunction ( ) ;
if (qFuzzyCompare (1 + dValuel, 1 + dValue2) ) {
//
}


,
45.

. 3.3 Qt, .
3. Qt 87

3.3. Qt

Qt C++

qint8 signed char 8

quint8 unsigned char 8

qint16 short 16

quintl6 unsigned short 16

qint32 Int 32

quint32 unsigned int 32

qint64 int64 long long 64

quint64 unsigned int64 unsigned long long 64

qlonglong To , qint64 64

qulonglong , quint64 64

. 3.3, qint64 quint64.


,
:
qDebug() "Number of bits for qint64 =" (sizeof(qint64) * 8);
qDebug() "Minimum of qint64 = -" ~(~quint64(0) 1);
qDebug() "Maximum of qint64 =" (~quint64(0) 1);
qDebug() "Number of bits for quint64 =" (sizeof(quint64) * 8)
qDebug() "Minimum of quint64 =" 0;
qDebug() "Maximum of quint64 =" -quint64(0);
:
Number of bits for qint64 = 64
Minimum of qint64 = -9223372036854775808
Maximum of qint64 = 9223372036854775807
Number of bits for quint64 = 64
Minimum of quint64 = 0
Maximum of quint64 = 18446744073709551615

Qt
,
. , ,
Qt (plug-ins),
Qt, . . QLibraryinfo
.
( 3.4).
88 I. Qt

3.4. QTiibrarylnfo

#include <QtCore>
int main(int argc, char** argv)
i
1
qDebug() "Build date:"
QLibrarylnfo::buildDate().toStringC'yyyy-MM-dd");
qDebug() "License Products:
QLibrarylnfo::licensedProducts();
qDebug() "Licensee:"
QLibrarylnfo::licensee();
qDebug() "Is Debug Build:"
QLibrarylnfo::isDebugBuild();

qDebug() "Locations";
qDebug() " Headers:"
QLibrarylnfo::location(QLibrarylnfo::HeadersPath);
qDebug() " Libraries: M
QLibrarylnfo::location(QLibrarylnfo::LibrariesPath);
qDebug() " Binaries:"
QLibrarylnfo::location(QLibrarylnfo::BinariesPath);
qDebug() " Prefix"
QLibrarylnfo::location(QLibrarylnfo::PrefixPath);
qDebug() " Documentation: "
QLibrarylnfo::location(QLibrarylnfo::DocumentationPath)
qDebug() " Plugins:"
QLibrarylnfo::location(QLibrarylnfo::PluginsPath);
qDebug() " Data:"
QLibrarylnfo::location(QLibrarylnfo::Datapath);
qDebug() " Settings:"
QLibrarylnfo::location(QLibrarylnfo::SettingsPath);

qDebug() " Examples:"


QLibrarylnfo::location(QLibrarylnfo::ExamplesPath);

Qt 5.3.1,
Windows:
Build date: "2014-05-20"
Build key: "Windows mingw debug full-config"
License Products: "OpenSource"
Licensee: "Open Source"
Is Debug Build: false
Locations
Headers: "C:/Qt/5.3.1/include"
Libraries: "C:/Qt/5.3.1/lib"
Binaries: "C:/Qt/5.3.1/bin"
Prefix "C:\Qt\5.3.1"
3. Qt 89

Documentation: ":/Qt/5.3.1/doc"
Plugins: "C:/Qt/5.3.1/plugins"
Data: "C:/Qt/5.3.I
Settings: "C:/Qt/5.3.1"
Examples: "C:/Qt/5.3.1/examples"

, Qt

.
qmake,
make- . ,
,
Qt.
Qt-, , ,
GDB.
4

, ?
,


.
,
.
,
.
.
Qt , Tulip
Qt, Qt.
STL (Standard Template Library,
), . ,
: Tulip STL.
, Tulip Qt .
Tulip ,
Qt .
, ,
, .
, ,
, ,
. Tulip ,
, .
Tulip Qtcore. Tulip (
STL) :
();
;
.
. 4.1.
4. 91

. 4.1. ,



,
. Qt ,
, .
, .
, , ,
.
,
.
. Qt
: (sequence containers)
(associative containters).
,
. .
: (vector), (list), (stack)
(queue). , Qt :
QVector<T> ;
QList<T> ;
QLinkedList<T> ;
QStack<T> ;
QQueue<T> .
,
,
. : (set),
() (hash). :
QSet<T> ;
QMap<K,> ;
QMultiMap<K,> ;
QHash<K,> ;
QMultiHash<K,> .
, . 4.1.
, , QSet<T>.
92 I. Qt

4.1. ,

== != ,

[] .
QSet<T> QLinkedList<T>,

begin ( ) constBegin() , ,
. QSet<T>

end ( ) constEnd() , ,

clear ( )

insert( )

remove ( )

size ( ) count( )
, ,
STL

value ( ) . QSet<T>

empty () isEmptyO true,


. ,
, STL


, , oobject,
,
private. , ,
, QObject,
.

!
, ,
empty (), size . : empty
, a size
,
.

.
.
, , - ,
, , ,
. , ,
.
4. 93

Qt :
Java;
STL.

foreach.

Java
Java .
, STL.
, ,
. ,
, next ( ) (. . 4.2)
. Java
, .
, STL:
QList<QString> list;
list "Within Temptation" "Anubis" "Mantus";
QListIterator<QString> it (list) ;
while (it .hasNext () ) {
.
qDebug ( ) "Element : " it next ( ) ;
}

. 4.2 QListiterator,
QLinkedListlterator, QVectorlterator, QHashlterator, QMapIterator QSetlterator.
, ,
.

4.2. QListiterator, QLinkedListlterator, QVectorlterator,


QHashlterator, QMapIterator, QSetlterator


toFront ( )
toBack ( )
hasNext ( ) true,
next ( )

peekNext ( )

hasPrevious ( ) true,

previous ( )

peekPrevious ( )

findNext (const T&)
findPrevious (consts T)
94 I. Qt

,
(mutable) .
, Mutable: QMutableListiterator,
QMutableHashlterator, QMutableLinkedListlterator, QMutableMapIterator QmutableVector-
iterator. remove ( ) , insert ( )
. setvalue ( )
.
" " "Rolling stones":
QList<QString> list;
list "Beatles" "ABBA" " M";
QMutableListIterator<QString> it (list) ;
while (it .hasNext () ) {
if ( it.next () == " M") {
.
it setvalue ( "Rolling Stones" ) ;
}
qDebugO it .peekPrevious ( ) ;
}

Java , ,
, ,
STL, .

STL
STL Java-
STL. , C++
. STL
, .
begin ( ) ,
, end ( ) , .
: , ,
, . ,
,
(. 4.2).

beginQ end()

. 4.2. begin ( ) , end ( )

++
. , ,
*. :
QVector<QString> vec;
vec "In Extremo" "Blackmore's Night" "Cultus Ferox";
QVector<QString>::iterator it = vec.begin));
4. 95

for (; it != vec.endO; ++it) {


qDebugO "Element:" *it;
}

:
Element: "In Extremo"
Element: "Blackmore's Night"
Element: "Cultus Ferox"

, it
: ++it,
, , .

, ++.
:
QVector<QString>::iterator it = vec.endO;
for (;it != vec.begin();) {
it;
qDebugO "Element:" *it;
}

:
Element: "Cultus Ferox"
Element: "Blackmore's Night"
Element: "In Extremo"
, ,
const iterator.
begin () end constBeginO constEndt).
, :
QVector<QString> vec;
vec "In Extremo" "Blackmore's Night" "Cultus Ferox";
QVector<QString>::const_iterator it = vec.constBegin();
for (; it != vec.constEnd(); ++it) {
qDebugO "Element:" *it;
}

,
STL, algorithm. ,
STL- sort ( ) :
QVector<QString> vec;
vec "In Extremo" "Blackmore's Night" "Cultus Ferox";
std::sort(vec.begin(), vec.end());
qDebugO vec;

:
QVector("Blackmore's Night", "Cultus Ferox", "In Extremo")

Qt , .
96 I. Qt

foreach
, C++ , ,
, ,
.
. :
QList<QString> list;
list "Subway to sally" "Rairmstein" "After Forever";
foreach (QString str, list) {
qDebugO "Element:" str;
}

foreach, , break, continue,


.

!
Qt foreach,
, .


,
. ,
, . 4.3.

4.3.

+= ( , )

at ()

back ( ) last ( ) .
, . back() last()
, ,
STL
contains ( ) ,

erase ( ) , ,

front ( ) first ( ) .
, . front ()
first () ,
, STL
indexOf ( )
.
: QLinkedList
4. 97

4.3 ()

lastlndexOf()

. : QLinkedList
mid() , ,

pop_back()
pop_front()

push_back() append() .
, ,
STL

push_front ( ) prepend() .
, ,
STL
replace() , ,
,

:
QVector<QString> vec;
vec.append("In Extremo");
vec.append("Blackmore's Night");
vec.append("Cultus Ferox");
qDebugO vec;
:
QVector("In Extremo", "Blackmore's Night", "Cultus Ferox")

QVector<T>
, (. 4.3).

,
. , ,
, .

!
push_front(), prependo, pop_front() remove ,

.
, insert .
, ,
-
, QLinkedList<T>.

I I I I I I I I I I I I I I I I I
. 4.3.
98 I. Qt

(. . 4.3)
push back( ) .
[] (. . 4.1), . :
QVector<int> vec;
vec.push_back(10);
vec.push_back(20);
vec.push_back(30);

qDebugO vec;
:
QVector(10, 20, 30)
.
0, .
, resize ()
(. 4.4).

4.4. QVector<T>

data() ( )
fill()
reserve()

resize()
toList() QList ,
toStdVector() std::vector ,

QByteArray
QVector<T>, ,
, , .
QByteArray ,
. ,
[ ] :
QByteArray arr(3);
arr[0] = arr[l] = OxFF;
arr[2] = 0x0;
QByteArray
. : qCompressO
qUncompress(). :
QByteArray = "Test Data";
QByteArray aCompressed = qCompress(a);
qDebug() qUncompress(aCompressed);

: "Test Data".
4. 99

, . ,
XML- (. 40). QByteArray
: toBase64 () fromBase64 ( ) .
, Base64.
.
, ,
:
QByteArray = "Test Data";
QByteArray aBase64 = a.toBase64();
qDebug() aBase64;

: "VGVzdCBEYXRh".
fromBase64():
qDebug() QByteArray::fromBase64(aBase64);

: "Test Data".
,
Base64 .

QBitArray
( ) .
, .
QByteArray.
bool.
: testBit ( )
setBit ( ) . [ ] ,
:
QBitArray bits(3);
bits[0] = bits[l] = true;
bits[2] = false;

QList<T> QLinkedList<T>
,
.
, ,

, .
,
.

!

size , ,
. , ,
, empty isEmptyO.

QList<T>.
(. 4.4).
100 I. Qt


1 2 -1
. 4.4.

. 4.5.

4.5. QList<T>

move()

removeFirst()
removeLast()

swap()

takeAt()

takeFirst()

takeLast()
toSet() QSet<T> ,
QList<T>
toStdList() STL std::list<T> ,
QList<T>

toVector() QVector<T> ,
QList<T>

, , ,
[].
at( ) , .

. :
QList<int> list;
list 10 20 30;

QValueList<int>::iterator it = list.begin();
while (it != list.endO) {
qDebugO "Element:" *it;
++it;
}

:
Element:10
Element:20
Element:30
4. 101

QList<T> ,
/ ,
QLinkedList<T>.
, QList<T>, (. 4.5),
,
.

: [ ] at().

. 4.5.

QStack<T>
, LIFO (Last In First Out,
), . . ,
(. 4.6).
QStack<T> .
QVector<T>.
(pushing),
(poping).
1,
1 . QStack<T> push()
pop ( ) . top ( ) .
.
QStack<QString> stk;
stk.push("Era");
stk.push("Corvus Corax");
stk.push("Gathering");

while (!stk.empty()) {
qDebugO "Element:" stk.popO;
}
:
. 4.6.
Element:"Gathering"
Element:"Corvus Corax"
Element:"Era"

QQueue<T>
, FIFO (First In First Out,
),
, , (. 4.7).
QQueue<T>, QList<T>.
102 I. Qt


:
QQueue<QString> que;
que.enqueue("Era");
que.enqueue("Corvus Corax");
que.enqueue("Gathering");

while (!que.empty()) {
qDebug() "Element:" que.dequeue();

}
. 4.7.
:

Element:"Era"
Element:"Corvus Corax"
Element:"Gathering"



. , .
( QSet<T>)
, . 4.6.

4.6.

contains() true,
. false

erase()
find() .
, ,
end()
insertMulti() .
, .
QSet<T>
insert() .
, .
QSet<T>

key()
. QSet<T>
keys() , .
QSet<T>

take()
. QSet<T>
unite()
values() ,
4. 103

QMap<K,T> QMultiMap<K,T>
, , ,
. ,
. ,
, .
(. 4.8), , (. 4.9).

. 4.8. . 4.9.

,
. QMap<K,>
,
, . ,
, > .
QMap<K,T> .
, , ,
, .
, ,
.
, (. 2),
. 4.7
QMap<K,>.

4.7. QMap<K, >

lowerBound() ,
toStdMap() STL ,
QMap<T>
upperBound() ,


[ ] . ,
key ( ) value ( ) , :
104 I. Qt

QMap<QString, QString> mapPhonebook;


mapPhonebook["Piggy"] = "+49 631322187";
mapPhonebook["Kermit"] = "+49 631322181";
mapPhonebook["Gonzo"] = "+49 631322186";
QMap<QString, QString>::iterator it = mapPhonebook.begin();
for (;it != mapPhonebook.end(); ++it) {
qDebug() "Name:" it.key()
" Phone:" it.valued;

:
Name:Gonzo Phone:+49 631322186
Name:Kermit Phone:+49 631322181
Name:Piggy Phone:+49 631322187

[],
, . ,
, , ,
. , ,
.
contains ( ) . :
if(mapPhonebook.contains( "Kermit")) {
qDebug() "Phone:" mapPhonebook["Kermit"];
}

,
, , , .
<, > ,
QMuitiMap<K, >. . 4.9,
Piggy:
QMultiMap<QString, QString> mapPhonebook;
mapPhonebook.insert("Kermit", "+49 631322181");
mapPhonebook.insert("Gonzo", "+49 631322186");
mapPhonebook.insert("Gonzo", "+49 631322000");
mapPhonebook.insert("Gonzo", "+49 631322010");
mapPhonebook.insert("Piggy", "+49 631322187");
mapPhonebook.insert("Piggy", "+49 631322999");

QMultiMap<QString, QString>::iterator it =
mapPhonebook.find("Piggy");
for (; it != mapPhonebook.end() && it.keyd == "Piggy"; ++it) {
qDebug() it.value() ;
}

QHash<K,T> QMultiHash<K,T>
<,>,
, -.
,
, >.
4. 105

, QMap<K,T>,
[ ] , ,
, , .
, contains( ) .
QHashcK,> ,
==
qHash ( ) . :
inline bool operator==(const MyClasss mcl, const MyClass& mc2)
{
return (mcl.firstName() == mc2.firstName()
&& mcl.secondName() == mc2.secondName()
);
}

qHash ( ) ,
. :
inline uint qHash(const MyClasss me)
{
return qHash(me.firstName()) A
qHash(me.secondName());
}

QMultiHash<K,T> QHash<K,>.
, , QMultiMapcK,>,
. , ,
. 4.8.

4.8. QHash<K, > QMultiHash<K, >


capacity ( ) -
reserve ( ) -
squeeze ( ) -

QSet<T>
, ,
. , Tulip, ,
QSet<T>,
,
, : , .
.
QSet<T> - QHashcK,>,
, .
. QSet<T>
.
. 4.10, , .
, , . 4.1 1.
106 I. Qt

1 2
. 4.10.


. 4.11.

. 4.10.
QSet<QString> setl;
QSet<QString> set2;
setl "Therion" "Nightwish" "Xandria";
set2 "Mantus" "Hagard" "Therion";
(. . 4.11, ) , ,
,
setResult:
QSet<QString> setResult = setl;
setResult.unite(set2);
qDebugO " = " setResult.toList();
:
= ("Xandria", "Hagard", "Mantus", "Nightwish", "Therion")

(. . 4.1 1, ).
setResult = setl;
setResult.intersect(set2);
qDebugO " setl c set2 = " setResult.toList();

,
:
setl set2 = ("Therion")
, ,
(. . 4.1 1, ):
setResult = setl;
setResult.subtract(set2);
qDebugO " setl c set2 = " setResult.toList();
setl set2 ,
:
setl set2 = ("Xandria", "Nightwish")
4. 107

. 4.9 QSet<T>.

4.9. QSet<T>

intersect() ,

reserve() -

squeeze() -

subtract() ,

toList() QList<T>,
QSet<T>

unite()

QtAlgorithms ,
, : , ,
. . ,
, ,
Tulip, . ,
qCopy():
QString values[] = {"Xandria", "Therion", "Nightwish", "Haggard"};
const int n = sizeof(values) / sizeof(QString);
QString copyOfValues[n];
qCopy(values, values + n, copyOfValues);

, ,
. ,
, -.
. 4.10 Tulip. Qt
, ,
STL.

4.10.

qBinaryFind()
qCopy() ,
qCopyBackward() ,
qCount()
qDeleteAll() . ,

108 I. Qt

4.10 ()

qEqual() . ,
==

qFill()

qFind()

qLowerBound() ,

qUpperBound() ,

qSort()

qStableSort()

qSwap()

- qSort () (. . 4.10).
, ,
. , QString
. QString:
QList<QString> list;
list "Within Temptation" "Anubis" "Mantus";
qSort(list);
qDebugO "Sorted list=" list;

:
Sorted list=("Anubis", "Mantus", "Within Temptation")
, :
qSort(list.begin(), list.endO, caseLessThan);


.
caseinsensitiveLessThan.

QGreater<T>, :
QList<int> list;
list 1 2 3 4 5 6;
qSort(list.begin(), list.endO, qGreater<int>());
qDebugO "Sorted list=" list;

:
Sorted list=(6, 5, 4, 3, 2, 1)
4. 109

- qFindO (. . 4.10).
, end ( ) ,
.
QList<QString> list;
list "Within Temptation" "Anubis" "Mantus";
QList<QString>::iterator it =
qFind(list.begin(), list.endO, "Anubis");
if (it != list.endO) {
qDebugO "Found=" *it;

else {
qDebug() "Not Found";
}

:
Found=Anubis

.
- qEqual() (. . 4.10).
,
.
QList<QString> list;
list "Within Temptation" "Anubis" "Mantus";

QVector<QString> vec(3);
vec[0] = "Within Temptation";
vec[l] = "Anubis";
vec[2] = "Mantus";

qDebugO "Equal="
qEqual(list.begin(), list.endO, vec.begin());
:
Equal=true

- , Mantus
Mantux, qEqual ( ) false.


-
. qFilio (. . 4.10).
Beatles:
QList<QString> list;
list "Within Temptation" "Anubis" "Mantus";
110 I. Qt

qFill (list .begin () , list.endO, "Beatles");


qDebugO list;

:
("Beatles", "Beatles", "Beatles")

. Qt
QString, , Unicode,
. QVector,
,
QChar, : .
QString ,
, : ,
, .
==, ! =, <, >, <=
>=. , :
QString str = "Lo";
bool M = (str == "Lo"); // bl = true
bool b2 = (str ! = "LO"); // b2 = true
isEmpty ( ) , .
, length (). QString

, ,
, . :
QString strl =
QString str2;
strl . isNull ( ) ; // false
.
str2 isNull ( ) ; // true

.
: , += +
append ( ) . :
QString strl = "Lo";
QString str2 = "stris";
QString str3 = strl + str2; // str3 = "Lostris"
strl .append (str2) ; //strl = "Lostris"

QString
replace ( ) . :

QString str = "Lostris";


str . replace ( "stris" , "gic"); // str = "Logic"

toLower ( ) toupper ( ) . :

QString strl = "LoStRiS";


QString str2 = strl .toLower () ; // str2 = "lostris"
QString str3 = strl .toUpper () ; // str3 = "LOSTRIS"
4. 111

setNumO .
number( ) . :
QString str = QString: inumber(35.123);

Qt.
:
QString str;
QTextStream(&str) 35.123;

,
.
,
. :
bool ok;
QString str = "234";
double d = str.toDouble(&ok);
int n = str.tolnt(&ok);
split ()
QStringList. : Ringo star:
QString str = "Ringo Star";
QStringList list = str.split(" ");

join () . , (Ringo star) ,
, :
str = list.join(" ");


Qt QRegExp.
. ,
.
. ,
, QString,
. 4. 11 ,
QRegExp.

4.11.

.
$ $
[] [abc]
- [] [0-9A-Za-z]

, [Adef]


A*b
112 I. Qt

4.11 ()

+ 1 +

1 ?

{} {3}

{, } {3, }

{, } {,3}

{n,m} m {2,3}

1 |

\ \
\ a\Bd
( ) (ab | ) ad

\d

\D ,

\s

\S ,

\w ,

\W ,

\A

\b

\B

\z (
)
\z ( )

,
. [ab] . ,
, [A-Z] ,
[a-z] , [0-9] .
, [a-z7]
7.
, . [0-9]
, .
. 4.11 .
, .
, { 4 , 5 } , ,
. ,
IP- , , ,
IP-:
4. 113

QRegExp reg("[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}");
QString strC'this is an ip-address 123.222.63.1 lets check it");
qDebugO (str.contains(reg) > 0); // true
,
(\), C++
. ,
. 4.11 , ,
, Iz2y3x4, IP-, , , .
|,
. ,
. :
QRegExp ("(.com|.ru)");
int nl = .indexln("www.bhv.ru"); // nl = 7 ( 7- )
int 2 = rxp.indexInCwww.bhv.de"); // n2 = -1 ( )
. 4.11 ( )
. , [a-zA-zo-9_]
\w.
(E-mail)
, regEmail:
QRegExp regEmail("([a-zA-Z0-9_\\-\\.]+)@([a-zA-Z0-9_.-])+\\.([a-zA-Z]{2,4} I
[0-9]{1,3}));
QString strEmaill = "Max.Schlee@neonway.com";
QString strEmail2 = "Max.Schlee#neonway.com";
QString strEmail3 = "Max.Schlee@neonway";
bool bl = regEmail.exactMatch(strEmaill); // = true
bool b2 = regEmail.exactMatch(strEmail2); //b2 = false
bool b3 = regEmail.exactMatch(strEmail3); //b3 = false

QVariant
QVariant , .
: int, unsigned int, double, bool, QString, QStringList, Qlmage,
QPixmap, QBrush, QColor, QRegExp . ,

,
. QVariant
.
QVariant
. :
QVariant vl(34);
QVariant v2(true);
QVariant v2("Lostris");

type () QVariant .
. ,
typeToName ( ) .
typeName ( ) , :
114 I. Qt

QVariant v(5.0);
qDebugO QVariant: itypeToName(v.type()); // =>double

QVariant ,
toT ( ) , . toT ( )
QVariant . :
QVariant v2(23);
int = v2.toInt() +5; // = 28


, QVariant Qtcore, toT ( )
QCoior, Qimage QPixmap . , QtGui, .

toT ( )
value<T>(). QVariant
:
QVariant v2(23);
int = v2.value<int>() + 5; //a = 28
QPixmap
QPixmap pix(":/myimg.png"); // QPixmap
QVariant vPix = pix; // QVariant,
QPixmap::operator QVariant()
QPixmap pix2 = vPix.value<QPixmap>(); // QPixmap QVariant


Qt
(. 4.12).
(shared data). Qt
.
,
1. , 1.
0, .
,
.
. 4.12 ,
, shared_null ( ).
, .
,
, .
,
, , ,
, .
,
0,
.
. 4.12 :
QString strl; // shared_null
QString str2; // shared_null
4. 115

strl = " " // , = 1


str2 = strl; // strl str2
// = 2
strl += " "; // strl

shared null

. 4.12.

, ,
.
, .
.
, , , : , .
. Qt
Java STL.
foreach.
,
, .
QString
.

.
QVariant , .


.
.

5.
6.
7.
8. ,
9.
10
11
12 , -
13
5


?
, ?

(GUI, Graphical
User Interface). (widgets)
.
, , ,
, ,
. Qt :
,
. , ,
.
, . 5.1, .
. , ,
: QMenu (. 31), QGLWidget (. 23), QMainWindow (. 34),
QGraphicsView (. 21).

QWidget
QWidget .
254 , 53 , ,
, , , .
QWidget, . 5.1, QObject, ,
/ .
, . ,
, Qt
.
, . ,
Ok Cancel () ,
. , -
, - .
(top-level widgets)
.
. - -
setGeometry ( ) ,
1

20
QObject QPaintDevice

-

QWidget
J
QDialog | QFrame QAbstractSpinBox QKey Sr:penceEdit |
QPageSetup Dialog QAbstractSc rollArea QDateTimeEdit QLineEdit

QA bstracIPrintDia log QAbstactl tern View QDateEdit QMacCocoaViewContainer

QPrintDialog QHeaderView QTimeEdit QMac Native Widget

QCoiorDialog QListView QDouble SpinBox QMainWindow

QErrorMessage QListWidget | QSpinBox | QMdi SubWindow

QFileDialoq QUndoView I QComboBox


QMenu

QFontDialog QTableView
-
C= QMenuBar
QFontComboBox
QinputDialog QTableWidget QPrintPreviewWidget
QAxWidget
QMessageBox QTreeView QProgressBar
-

QPageSet upDialog QTree Widget QColumn ViewGrip QRubberBand

QProgressDialog QCol umnView QDesignerActionEditorlnterface QSizeGrip

QWizard QGraphicsView QDesignerForm Windowlnterlace QSplashScreen I

QMdiArea QDesiynerObjectl ns pector Interface QSplitterHandJe

QPIainTextEdit QDesignerPropertyEditorlnterface QStatusBar


QAbstractButton


QScrollArea QDesignerWidgetBoxinterface QSvgWidget
QCheckBox
QTextEdil QDesktopWidget QTabBar
QPushButton
I_
QTextBrowser QDialogButtonBox QTabWidget
QRadioButton
II.


QDockWidget QToolBar
QToolButton QLCDNumber |
QFocusFrame QWizard Page
QJ_abel I
QAbstractSlider
QGLWidget


QSplitter I
QDial
QGroupBox
QStackedWidget I
QScrollBar
QToolBox
QSlider

. 5.1.
5. ? 121

(layouts) (. 6). show(),


hide ( ) .

, , ,
show() , , - .

Qwidget
:
QWidget (QWidget* pwgt = 0, Qt : :WindowFlags f = 0)

, ,
. , ,
. Qt: :WindowFiags
,
( . .).
,
, (. 5.2) ,
|.
setWindowFlags ( ) . :
.
wgt setWindowFlags (Qt : :Window I Qt : :WindowTitleHint I
Qt: :WindowStaysOnTopHint) ;

. 5.2 .


_ Title

QtcWmdow Qt;(Window
i Qt :Window SystemMonoHri I QtcWrkdowMajdnrBzeButtonl-fcnt

Trite _ Title -===


Qt::Window Qt "Window
lQt::WndowTtleHrt i Qt::WmdowMrwnize8uttonhlnt

!Title
Qt:Window
l Gl::FfBmetessWndowHnt Qt:(Window
II Qt; WndowContodHdpButtonHnt

. 5.2.
122 II.


Qt : :WindowStaysOnTopHint , ,
.

- setwindowTitle ( ) .
. :
wgt . setwindowTitle ( " Window" ) ;

setEnabled ( ) (enabled) (disabled)


. true , a false
.
, , isEnabledO .
,
(. 14). ,
: mousePressEvent ( ) , mouseMoveEvent ( ) ,
mouseReleaseEvent ( ) mouseDoubleClickEvent ( ) .


(. 5.3).
, .
size ( ) , height ( ) width ( ) . , height ( )
width ( ) , ,
size ( ) QSize (. 17), .

width ()

. 5.3. ( )

( ) , ( ) pos ( ) .
X Y, pos ( ) QPoint
(. 17), .
geometry () QRect (. 17),
.
move(), resize ().
:
pwgt ->move ( 5, 5 ) ;
pwgt->resize (260, 330);

, ,
setGeometry ( ) .
5. ? 123

X , Y, , .
, move()
resize():
pwgt->setGeometry(5, 5, 260, 330);


(Backing Store)
,

(PaintEvent). , .
,
,
, .
.


, .

(. 13), setPaletteO
.
autoFillBackground, false.
, , .
true,
, . :
wgt.setAutoFillBackground(true);

5.1 wgt,
( pwgti pwgt2) .

5.1. main.cpp

#include <QtWidgets>
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QWidget wgt;

QWidget* pwgti = new QWidget(&wgt);


QPalette pall;
pall.setColor(pwgtl->backgroundRole(), Qt::blue);
pwgtl->setPalette(pall);
pwgtl->resize(100, 100);
pwgtl->move(25, 25);
pwgtl->setAutoFillBackground(true);

QWidget* pwgt2 = new QWidget(&wgt);


QPalette pa!2;
124 II.

12.setBrush(pwgt2->backgroundRole(), QBrush(QPixmap(":/stone.jpg")));
pwgt2->setPalette(pal2);
pwgt2->resize(100, 100);
pwgt2->move(75, 75);
pwgt2->setAutoFillBackground(true);

wgt.resize(200, 200);
wgt.show();

return app.exec();
)

setPaiette ( ) ,
(). ( resize )
- ( move ( ) )
setAutioFillBackround ( ) autoFillBackground true,
.
- ( pwgt2)
, .
,
stone.jpg
12.
,
(. 5.4).

. 5.4.


() QCursor QCursor.
,
. ,
. , , ,
, ,
.
setcursorf),
. 5.1 .

5.1. CursorShape Qt

,
ArrowCursor . ,

5. ? 125

5.1 ()

, .
UpArrowCursor
T

CrossCursor
+ . ,

WaitCursor
I ,

l- (I-beam cursor),
IbeamCursor I .
,

PointingHandCursor
,

, -
,
ForbiddenCursor
0 ,

WhatsThisCursor ,
-
,
SizeVerCursor
i
,
SizeHorCursor 4

SizeBDiagCursor ,

,
SizeFDiagCursor \


,
SizeAllCursor

,
SplitVCursor JL
T . 6
,
SplitHCursor Hh
. 6

OpenHandCursor
a ,

,
ClosedHandCursor n
,
BlankCursor


QGuiApplication::setOverrideCursor ( )
. , ,
, ,
.
126 II.

,
QGuiApplication: : setOverrideCursor (Qt : :WaitCursor) .
,
QGuiApplication:: restoreOverrideCursor ( )
.

QCursor pos ( ) ,
. set Pos ( )
.
,
QBitmap. ,
. ,
coiorl, , ,
colorO
.
QPixmap.
( 5.2), . 5.5, .

. 5.5.

5.2.

# include <QtWidgets>

int main(int argc, char** argv)


{
QApplication app(argc, argv) ;
QWidget wgt;
QPixmap pix ( " : /clock . png" ) ;
QCursor cur (pix);

.
wgt setCursor (cur) ;
.
wgt resize (180, 100);
.
wgt show ( ) ;

return app . exec ( ) ;


}

5.2 wgt,
pix,
png-,
(
QPixmap 19). -
5. ? 127

QCursor setCursor ( )
.


QStackedwidget QFrame ,
.
addwidget ( ) .
.
removewidget(),
.
setCurrentwidget ( )
setCurrentindexO, .
indexOf ( ) , .

QFrame QWidget
. (. . 5.1).
, setFrameStyle ( ),
.
| ().
(. 5.2): QFrame:: Raised, QFrame::Plain QFrame::Sunken.
.

5.2.
128 II.


(. . 5.2): QFrame::Box, QFrame::Panel, QFrame::WinPanel, QFrame::HLine QFrame::
VLine. , , setFrameStyle()
QFrame::NoFrame.
setContentsMargin ( ) QWidget
, setbinewidth( ) setMidLineWidth ( )
.
QFrame pfrm = new QFrame;
pfrm->setFrameStyle(QFrame::Box | QFrame::Sunken);
pfrm->setLineWidth(3);

, setFrameStyle ()

, setbinewidth() .


QAbstractScrollArea QFrame
.
QScrollArea.
,
, /
. .
, ,
Qt::ScrollBarAlwaysOn. :
QScrollArea sa;
sa.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
sa.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
. 5.6,
, .
.
QAbstractScrollArea::viewport () . verticalScrollBar ( )
horizontalScrollBar ()
( QScrollBar) . cornerwidget ( )
, .

|viewport()
|verticalScrollBar()
_
.
id ' jcornerWidgetQ
horizontalScrollBar()
. 5.6.
5. ? 129

setwidgeto,
.
.
widget () . QScrollArea
removeChild().
. 5.7 (
5.3). .

. 5.7.

5.3. main.cpp

#include <QtWidgets>

int main(int argc, char** argv)


{
QApplication app(argc, argv);
QScrollArea sa;

QWidget* pwgt = new QWidget;


QPixmap pix(":/img.jpg");

QPalette pal;
pal.setBrush(pwgt->backgroundRole(), QBrush(pix));
pwgt->setPalette(pal);
pwgt->setAutoFillBackground(true);
pwgt->setFixedSize(pix.width(), pix.height());

sa.setWidget(pwgt);
sa.resize(350, 150);
sa.show();

return app.exec();
}

5.3 sa.
( pwgt) pix.
img.jpg,
130 II.

setPalette ( ) . ,
setAutoFillBackground ( ) .
( pwgt)
setFixedSize () . sa
setwidget ( ) .

(
). QWidget . ,
Qt, QWidget
.
-
.
, (show) (hide), ,
.
-
.
, -
, , .
. Qt
, .
.
Q Frame QWidget ,
.
QStackedwidget
. , ,
.
.
,
.
6

(Layouts) Qt (
). ,
,
, .
, ,
.
.
, ,
. , ,
.
Visual Basic,
.
,
, , ,
,
,
. Qt
. ,
, , ,
.
Qt ,
.
, ,
/ . .

(layout managers)
,
, .
.
132 II.

QLayout
, : QObject QLayoutitem (. 6.1).
QLayout.

[QLayoutitem 1 QObject

| QFormLayout

[ QGridLayout
[ QStackedLayout |
QBoxLayout

[QHBoxLayout
]
(_QVBo*Layou_ |setMargin() setSpacingQ

. 6.1. . 6.2.


,
,
Qt.
, QLayout, additemO, count (),
setGeometry(), takeAt() itemAt().

QLayout QGridLayout QBoxLayout (. . 6.1).


QGridLayout , QBoxLayout
QHBoxLayout QVBoxLayout .
.
. setSpacing(),
. setMargin ( )
5
10 . 6.2
.
addwidget ( ) ,
addLayout ( ) .
- ,
removewidget( ) , .

.
,
.


-. , ,
, .
6. 133



QHBoxLayout QVBoxLayout.
QBoxLayout
QHBoxLayout QVBoxLayout, QBoxLayout, ,
,
, .
:
.

QBoxLayout
QBoxLayout ,
. ,
:
LeftToRight , ;
RightToLeft , ;
TopToBottom , ;
BottomToTop , .
QLayout :
insertwidget ( ) , insertLayout { ) ,
insertspacing () insertStretch ( . )

addspacing ( )
.
QBoxLayout addwidget ( )
, ,
( ).
. 6.3, 6.1.
s
I Stretch :
l A l _
6_ IL c I
. 6.3.

6.1. main.cpp
#include <QtWidgets>

int maintint argc, char** argv)


{
QApplication app(argc, argv);
QWidget wgt;

QPushButton* pcmdA = new QPushButton ("A");


QPushButton* pcmdB = new QPushButton ("B");
QPushButton* pcmdC = new QPushButton ("C");
134 II.

//Layout setup
QBoxLayout* pbxLayout = new QBoxLayout(QBoxLayout::LeftToRight);
pbxLayout->addWidget(pcmdA, 1);
pbxLayout->addWidget(pcmdB, 2);
pbxLayout->addWidget(pcmdC, 3);
wgt.setLayout(pbxLayout);

wgt.resize(450, 40);
wgt.show();

return app.exec();
)

6.1 , ,
QBoxLayout::addwidget ( ) ,
.
QBoxLayout::LeftToRight,
. QWidget::setLayout ( )
wgt.
, 6.1 ,
( pcmdA, pcmdB pcmdc) -,
, ,
. - ?
, (memory leak)?
, -
. setLayout ( )
wgt.
,
addStretch ( ) .
,
. . 6.4
.


. 6.4.

( 6.2), . 6.5,
-

. 6.5.
6. 135

(. 6.1), . 6.3,
.

6.2. main.cpp

#include <QtWidgets>

int mainfint argc, char** argv)


{
QApplication apptargc, argv);
QWidget wgt;

QPushButton* pcmdA = new QPushButton("A");


QPushButton* pcmdB = new QPushButton("B");

//Layout setup
QBoxLayout* pbxLayout = new QBoxLayout(QBoxLayout::LeftToRight);
pbxLayout->addWidget(pcmdA);
pbxLayout->addStretch(1);
pbxLayout->addWidget(pcmdB);
wgt.setLayout(pbxLayout);

wgt.resize(350, 40);
wgt.show();

return app.exec( );
)

6.2 QWidget .
QLayout::
addwidget() ( pcmdA). QBoxLayout::
addStretchf) , (
pcmdB).

QHBoxLayout
QHBoxLayout
. QBoxLayout,
,
, . ,
QHBoxLayout ( 6.3), . 6.6.

OHBonlayotrt

1 ] 1 1 1 1
. 6.6.
136 II.

6.3. main.cpp

#include <QtWidgets>

int main(int argc, char** argv)


{
QApplication app(argc, argv);
QWidget wgt;

QPushButton* pcmdA = new QPushButton("A");


QPushButton* pcmdB = new QPushButton("B");
QPushButton* pcmdC = new QPushButton("C");

//Layout setup
QHBoxLayout* phbxLayout = new QHBoxLayout;
phbxLayout->setMargin(10);
phbxLayout->setSpacing(20);
phbxLayout->addWidget(pcmdA);
phbxLayout->addWidget(pcmdB);
phbxLayout->addWidget(pcmdC);
wgt.setLayout(phbxLayout );

wgt.show();

return app.exec( );
}
6.3 , ( pcmdA, pcmdB pcmdc).
QHBoxLayout .
QLayout : :setMargin ( ) 10 .
QLayout : : setspacing ( ) 20 .
QLayout::addwidget() .

QVBoxLayout
QVBoxLayout QBoxLayout
. QBoxLayout
QHBoxLayout. 6.3 QHBoxLayout QVBoxLayout,
, . 6.7.

. 6.7.
6. 137


,
. addLayoutO,
.
. 6.8
( 6.4). QVBoxLayout QHBoxLayout.

_ Layout
QVBoxLayout

QHBoxLayout

. 6.8.

6.4. Layout.cpp

#include <QtWidgets>

int main(int argc, char** argv)


{
QApplication app(argc, argv);
QWidget wgt;

QPushButton* pcmdA = new QPushButton("A");


QPushButton* pcmdB = new QPushButton("B");
QPushButton* pcmdC = new QPushButton("C");
QPushButton* pcmdD = new QPushButton("D");

QVBoxLayout* pvbxLayout = new QVBoxLayout;


QHBoxLayout* phbxLayout = new QHBoxLayout;
phbxLayout->setMargin(5);
phbxLayout->setSpacing(15);
phbxLayout->addWidget(pcmdC);
phbxLayout->addWidget(pcmdD);

pvbxLayout->setMargin(5);
pvbxLayout->setSpacing(15);
pvbxLayout->addWidget(pcmdA);
pvbxLayout->addWidget(pcmdB);
pvbxLayout->addLayout(phbxLayout);
wgt.setLayout(pvbxLayout );
wgt.show();

return app.exec();
138 II.

6.4 , . 6.8.
, ,
, .
setMargin(), ,
setspacing () 15 ,
. pcmdc pcmdD.
pcmdA pcmdB QLayout : : addwidget ( )
pvbxLayout, QBoxLayout : :
addLayout ( ) phbxLayout.
Qwidget : : setLayout ( ) pvbxLayout wgt.

QGridLayout
QGridLayout,
. ,
.

, ,

QFormLayout, ,
QGridLayout. , ,
, ,
.

addRow(), :
.
addwidget ( ) ,
, . ,
, addwidget ( ) ,
, .
(. . 7.1 7), ,
:
playout->addWidget (widget, 17, 1, Qt : :AlignCenter) ;

setRowStretch ( ) setColumnStretch ( ) ,
, .
setspacing { ) .
, . 6.9 ( 6.5), : , , D
2 2 .

. 6.9.

6.5. main.cpp

#include <QtWidgets>

int main(int argc, char** argv)


6. 139

{
QApplication app(argc, argv);
QWidget wgt;

QPushButton* pcmdA = new QPushButton("A");


QPushButton* pcmdB = new QPushButton("B");
QPushButton* pcmdC = new QPushButton("C");
QPushButton* pcmdD = new QPushButton("D");

QGridLayout* pgrdLayout = new QGridLayout;


pgrdLayout->setMargin(5);
pgrdLayout->setSpacing(15);
pgrdLayout->addWidget(pcmdA, 0, 0);
pgrdLayout->addWidget(pcmdB, 0, 1);
pgrdLayout->addWidget(pcmdC, 1, 0);
pgrdLayout->addWidget(pcmdD, 1, 1);
wgt.setLayout(pgrdLayout );

wgt.show();

return app.exec();
}

6.5 pgrdLayout.
setMarginf) 5 . setspacing
15 .
addwidget ( ) ,
, .
( 6.6), . 6.10,
.
QValueStack QRegExp, 4.

QGridLayout

1 7 793

7 8 9 /

4 5 6 *

1 2 3 -

0 = +

. 6.10. ,

140 II.

6.6. main.cpp

#include <QApplication>
#include "Calculator.h"

int main(int argc, char** argv)


{
QApplication app(argc, argv);
Calculator calculator;

calculator.setWindowTitle("Calculator");
calculator.resize(230, 200);

calculator.show();

return app.exec();
}

, 6.6, calculator
(. 6.7-6. 1 1). resize () show()
.
Calculator, 6.7, :
m plcd , m stk
m_strDisplay ,
. createButton ( )
, calculate ( )
,
m stk. slotButtonClickedO
.

6.7. Calculator.!!

#pragma once

#include <QWidget>
#include <QStack>

class QLCDNumber;
class QPushButton;

class Calculator : public QWidget {


Q_OBJECT
private:
QLCDNumber* m_plcd;
QStack<QString> m_stk;
QString m_strDisplay;

public:
Calculator(QWidget* pwgt = 0);
6. 141

QPushButton* createButton(const QSt rings str);


void calculate ( );

public slots:
void slotButtonClicked ();
};

( 6.8)
, 12. QLCDNumber::Flat, setSegmentStyle ( ),
. setMinimumSize ( )
. aButtons
.
addwidget ( ) ,
,
.
, createButton ( ) ,
addwidget () (1,3) (
).
createButton ( ) addwidget ( ).

6.8. Calculator.cpp. Calculator

Calculator::Calculator (QWidget* pwgt/*= 0*/) : QWidget (pwgt)


{
m_plcd = new QLCDNumber(12);
m picd->setSegment St yle(QLCDNumber::Flat)i ;
m plcd->setMinimumSize(150, 50);

QChar aButtons[4][4] = {{'7', '8', '9', '/'}


1

4', '5', '6', '*'}


1

{'14 '2', '3', 1


_i
r ' +'}
i
('O',

//Layout setup
QGridLayout* ptopLayout = new QGridLayout;
ptopLayout->addWidget (m_plcd, 0, 0, 1, 4);
ptopLayout ->addWidget (createButton("CE"), 1, 3);

for (int i = 0; i < 4; ++i) {


for (int j = 0; j < 4; ++j ) {
ptopLayout->addWidget (createButton(aButtons[i][j]), i + 2, j);
}
}
setLayout (ptopLayout);

createButton(), 6.9,
. setMinimumSize () -
142 II.

, clicked ()
slotButtonClicked() connect().

6.9. Calculator.cpp. createButton()

QPushButton* Calculator::createButton(const QStrings str)


{
QPushButton* pcmd = new QPushButton(str);
pcmd->setMinimumSize(40, 40);
connect(pcmd, SIGNAL(clicked()), SLOT(slotButtonClicked()));
return pcmd;
}

calculate () ( 6.10) ,
m_stk. dOperand2 ,
double. strOperation
. dOperandl ,
double. if
, , ,
dResult. dislay ()
dResult ( m plcd).

6.10. Calculator.cpp. calculate ()

void Calculator::calculate()
{
double dOperand2 = m_stk.pop().toDouble();
QString strOperation = m_stk.pop();
double dOperandl = m_stk.pop().toDouble();
double dResult = 0;

if (strOperation == "+") {
dResult = dOperandl + dOperand2;
}
if (strOperation == {
dResult = dOperandl dOperand2;
}
if (strOperation == "/") {
dResult = dOperandl / dOperand2;
}
if (strOperation =="*") {
dResult = dOperandl * dOperand2;
}

m_plcd->display(dResult);
}

slotButtonClicked () ( 6.11) ,
, QPushButton, str
6. 143

. ,
0. ,
m strDisplay,
. ,
. ,
.
calculate ( ) .
clear () ,
, . =,
.

6.11. Calculator.cpp. slotButtonClicked()

void Calculator::slotButtonClicked ( )
{
QString str = ((QPushButton* ) sender ( ) )->text ( );

if (str == "CE") {
m_stk.clear ();
m_strDisplay =
m_plcd->display("0");
return;
}
if (str.contains(QRegExp("[0-9]"))) {
m_strDisplay += str;
m_plcd->display(m_strDisplay.toDouble ());
}
else if (str == {
m_strDisplay += str;
m_pl cd->displ ay(m_st r Display);
}
else {
if (m_stk.count () >= 2) {
m_st k.push(QString ().setNum(m_plcd->value ( ) ) ) ;
calculate ();
m_stk.clear ();
m_st k.push(QString ( ).setNum(m_plcd->value ( ) ) );
if (str ! = "=") {
m_stk.push(str);
}
}
else {
m_stk.push(QString ().setNum(m_plcd->value ( ) ) ) ;
m_strDisplay =
m_plcd->display ( "0");
}
144 II.


.

<>,
. ,

. . 6.11 .

, .

. 6.11. . 6.12.

QWidget::
setTabOrder ( ) ,
.
, . 6.11,
, . 6.12:
QWidget::setTabOrder(, );
QWidget::setTabOrder(, );

QSplitter

.
, ,
.
(Windows Explorer) Windows.
QSplitter, QSplitter.
, .
,
, .
,
, setOpaqueResize ( ) , true.
, . 6.13, QTextEdit ( 6.12).

6.12. main.cpp

#include <QtWidgets>

int main(int argc, char** argv)


{
QApplication app(argc, argv);
6. 145

QSplitter spl (Qt : : Vertical ) ;


QTextEdit* ptxtl = new QTextEdit;
QTextEdit* ptxt2 = new QTextEdit;
spl . addwidget (ptxtl ) ;
spl . addwidget (ptxt2 ) ;

ptxtl->setPlainText ( "Linel\n"
"Line2\n"
"Line3\n"
"Line4\n"
"Line5\n"
"Line6\n"
"Line7\n"
);
ptxt2->setPlainText (ptxtl->toPlainText ( ) ) ; . 6.13.

spl . resize (200, 220);


spl . show ( ) ;

return app . exec ( ) ;


}

6.12 QSlitter Qt: :vertical , ,


.


QSplitter :: Horizontal. ,
QSplitter: horizontal QSplitter: :Vertical setOrientation ( ) .

QTextEdit ,
QSplitter: : addwidget () . QTextEdit
setPlainText ( ) .


. Qt ,
, .
.
: QObject QLayoutitem.

. ,
.

. ,
.
7


.
,


.
, (, ).


,
. , ,
. ,
, .
QLabel QLabel.
QFrame .
, ,
setText ( ) , setPixmap ( ) setMovie ( ) .
setAlignment ( ) .
, . 7.1.
, ,
| ().
AlignCenter, AlignVCenter AlignHCenter.

7.1. AligrmentFlag Qt


AlignLeft 0x0001
AlignRight 0x0002
AlignHCenter 0x0004
AlignJustify 0x0008
AlignTop 0x0010
7. 147

7.1 ()


AlignBottom 0x0020
AlignVCenter 0x0040
AlignCenter AlignVCenter | AlignHCenter

. 7.1,
,
HTML (HyperText Markup Language,
). ( 7.1)
HTML ,
.

. 7.1.
HTML

7.1. main.cpp

#include <QtWidgets>

int main(int argc, char** argv)


{
QApplication app(argc, argv);

QLabel lbl("<HlXCENTER>QLabel - HTML Demo</CENTERX/Hl>"


"<H2><CENTER>Image</CENTERXH2>"
"CCENTERXIMG BORDER=\"0\" SRC=\":/Balalaika.png \"></CENTER>"
"<H2><CENTER>List</CENTERXH2>"
"<OLXLI>One</LI>"
" <LI>Two</LI>"
" <LI>Three</LI>"
"</0L>"
148 II.

" <2 ><CENTER> Font Style</ CENTERXH2>"


"<CENTER><FONT COLOR=RED>"
" <B>Bold</B>, <I>Italic</I>, <U>Underline</U>"
"< / FONTX / CENTER> "
"<H2><CENTER>Table</CENTER></H2>"
"<CENTER> <TABLE>"
" <TR BGCOLOR=# ff00ff>"
" <TD>1, 1</TDXTD>1, 2</TDXTD>l, 3</TDXTD>l, 4</TD>"
M
</TR> "
" <TR BGCOLOR=YELLOW>"
" <TD>2, 1</TDXTD>2, 2</TDXTD>2, 3</TDXTD>2, 4</TD>"
M
</TR>"
" <TR BGCOLOR=#OOfOOO>"
" <TD>3, 1</TDXTD>3, 2</TDXTD>3, 3</TDXTD>3, 4</TD>"
M
</TR>
"</TABLE> </CENTER>"
);
lbl . show ( ) ;

return app . exec ( ) ;


}

7. 1 lbl
HTML.
- setText ( ) . ,
0, .
( 7.2), . 7.2,

HTML.

. 7.2.

7.2. main.cpp

# include <QtWidgets>

int main(int argc, char** argv)


{
QApplication app (argc, argv);
7. 149

QPixmap pix;
pix.load(":/mira.jpg");

QLabel lbl;
lbl.resize(pix.size());
lbl.setPixmap(pix);

lbl.show();

return app.exec();
}

7.2, QPixmap.
ioad() mira.jpg.
lbl QLabel.
resize ()
. , , setPixmap ()
.
setBuddyO
. & (), ,
, . <Alt>
, setBuddyO. . 7.3
, 7.3 .

. 7.3.
&

7.3. main.cpp

#include <QtWidgets>

int main(int argc, char** argv)


{
QApplication app(argc, argv);

QWidget wgt;
QLabel* plblName = new QLabel("&Name:");
QLineEdit* ptxtName = new QLineEdit;
plblName->setBuddy(ptxtName);

QLabel* plblAge = new QLabel("&Age:");


QSpinBox* pspbAge = new QSpinBox;
plblAge->setBuddy(pspbAge);
150 II.

//Layout setup
QVBoxLayout* pvbxLayout = new QVBoxLayout;
pvbxLayout->addWidget(plblName);
pvbxLayout->addWidget(ptxtName);
pvbxLayout->addWidget(plblAge);
pvbxLayout->addWidget(pspbAge);
wgt.setLayout(pvbxLayout );

wgt.show();

return app.exec();
)

7.3 wgt QWidget ,


- 0.
-,

QVBoxLayout. Name () N
. . ,
setBuddyO ,
.
Age (), ( QSpinBox) .
.
, , ,
HTML-.
III.
. , QLabei
linkActivatedO,
, .
, , ,
QLabei , Web- (
QDesktopServices::openUrl ()).
setOpenExternalLinks ( ) true. :
QLabei* plbl =
new QLabei("< HREF=\"http://www.bhv.ru\"> www.bhv.ru</A>");
1.setOpenExternalLinks(true);


(progress bar) ,
.
. ,
, ,
, . ,
. QProgressBar
QProgressBar. -
7. 151

, , setOrientation ( ) Qt::vertical,
.
.
Step () .
Reset () . ,
7.4, , . 7.4.

40% Step Reset

. 7.4.

7.4. main.cpp

#include <QApplication>
#include "Progress.h"

int main (int argc, char** argv)


{
QApplication app(argc, argv);
Progress progress;

progress.show();

return app.exec();
)

7.5 Progress.h, Progress,


Qwidget. :
, . :
slotstep ( ) slotReset ( ) . ,
.

7.5. Progress.h

#pragma once

#include <QWidget>

class QProgressBar;

// ----
----
======================
class Progress : public QWidget {
Q_0BJECT
private:
QProgressBar* m_pprb;
int m_nStep;
152 II.

public:
Progress(QWidget* pobj = 0);

public slots:
void slotStep ();
void slotReset();
};

( 7.6) m nstep 0.
setRange ( ) ,
5, setMinimumwidth ( )
, .
setAlignment () Qt::AlignCenter
(. . 7.1). : Step ()
Reset (), slotStep( ) slotReset().
slotStep () m nstep 1
QProgressBat::setvalue ( ) . slotReset
m nstep 0 , QProgressBar::reset(),
. -
Progress
QVBoxLayout, , , -.

7.6. Progress.cpp

tinclude <QtWidgets>
#include "Progress.h"

//
Progress::Progress(QWidget* pwgt/*= 0*/)
: QWidget(pwgt)
, m_nStep(0)
{
m_pprb = new QProgressBar;
m_pprb->setRange(0, 5);
m_pprb->setMinimumWidth(200);
m_pprb->setAlignment(Qt::AlignCenter);

QPushButton* pcmdStep = new QPushButton("&Step");


QPushButton* pcmdReset = new QPushButton("&Reset");

QObject::connect(pcmdStep, SIGNAL(clicked()), SLOT(slotStep()));


QObject::connect(pcmdReset, SIGNAL(clicked()), SLOT(slotReset()));

//Layout setup
QHBoxLayout* phbxLayout = new QHBoxLayout;
phbxLayout->addWidget(m_pprb);
phbxLayout->addWidget(pcmdStep);
phbxLayout->addWidget(pcmdReset);
setLayout(phbxLayout);
)
,,
7. 153

void Progress::slotStep()
{
m_pprb->setValue(++m_nStep);
}
//
void Progress::slotReset()
{
m_nStep = 0;
m_pprb->reset();
}


QLCDNumber
QLCDNumber.
, , .
. ,
,
setSmallDecimalPoint () true false .

setNumDigits () . ,
, overflow().
Outline,
, setSegmentstyle ( ) : QLCDNumber::
Outline, QLCDNumber::Filled QLCDNumber::Flat. . 7.2
.

7.2.


Outline

Flat
/
Filled ~1
J I

, ,
.
setModeO, :
QLCDNumber::Bin (), QLCDNumber::Oct (), QLCDNumber::Dec (
) QLCDNumber:: ().
setBinMode(), setOctMode(), setDecModeO setHexModeO
.
154 II.

( 7.7) ,
(. 7.5).
7.7 ( pled)
( pspb). setsegmentstyle()
. setModeO
QLCDNumber::Hex .
setFixedHeight() , 30.
valueChanged() display()
.

. 7.5.

7.7. main.cpp

#include <QtWidgets>

int main (int arge, char** argv)


{
QApplication app(argc, argv);

QWidget wgt;
QLCDNumber* pled = new QLCDNumber;
QSpinBox* pspb = new QSpinBox;

plcd->setSegmentStyle(QLCDNumber::Filled);
plcd->setMode(QLCDNumber::Hex);

pspb->setFixedHeight(30);

QObject::connect(pspb, SIGNAL(valueChanged(int)),
pled, SLOT(display(int))
);

//Layout setup
QVBoxLayout* pvbxLayout = new QVBoxLayout;
pvbxLayout->addWidget(pled);
pvbxLayout->addWidget(pspb);
wgt.setLayout(pvbxLayout );

wgt.resize(250, 150);
wgt.show();

return app.exec();
7. 155

.
,
. ,
HTML. .

.
.

, .
: , ,
.
8

, ,
.


. ,
,
. (on) (off).

?
QAbstractButton
QAbstractButton .
: (QPushButton),
, (QCheckBox) (QRadioButton).
QAbstractButton , .
, .


,
, setText ( ) .
QAbstractButton text ( ) .

seticon().
seticonSize ()
, (
).
iconSize () . , ,
, icon ( ) .


QAbstractButton
:
clicked ( ) ;
pressed ( ) ;
8. , 157

released ( ) ;
toggled ( ) ,
.


QAbstractButton :
isDown()
true, .
, ,
setDown( ) ;
isCheckedO
true,
. , ,
setChecked ( ) ;
,
, isEnabledO
true.
setEnabled().

, ,
Ok Cancel () .
.
, ,
. QPushButton
QPushButton.
:
QPushButton* pcmd = new QPushButton(" Button");
( ) . ,
, ,
.
, clicked () .
, <Enter>,
, ( ).
, setDefault().
, . 8.1,
:
Normal Button ( ) ,
.
;
Toggle Button () :
, .
, ,
;
Flat Button ( )
. . , , -
158 II.

,
;
, Pixmap Button ( )
, .
8.1 ,
. 8.1.
( pcmdNormai). - (
pcmdToggie) , ,
setcheckabie ( )
true .
setChecked ( ) true
.

. 8.1.

( pcmdFlat) .
set Flat ( ) true .

pix, ChordsMaestro.png,
. ( pcmdPix),
seticono . seticonSizeO
,
, size ( ) QPixmap.

8.1. main.cpp

#include <QtWidgets>

int main (int argc, char** argv)


{
QApplication app(argc, argv);

QWidget wgt;
QPushButton* pcmdNormai = new QPushButton("SNormal Button");

QPushButton* pcmdToggie = new QPushButton("SToggle Button");


pcmdToggle->setCheckable(true);
pcmdToggle->setChecked(true);

QPushButton* pcmdFlat = new QPushButton("&Flat Button");


pcmdFlat->setFlat(true);

QPixmap pix(":/ChordsMaestro.png");
QPushButton* pcmdPix = new QPushButton("SPixmap Button");
pcmdPix->setIcon(pix);
pcmdPix->setIconSize(pix.size());

//Layout setup
QVBoxLayout* pvbxLayout = new QVBoxLayout;
8. , 159

pvbxLayout->addWidget(pcmdNormal);
pvbxLayout->addWidget(pcmdToggle);
pvbxLayout->addWidget(pcmdFlat);
pvbxLayout->addWidget(pcmdPix);
wgt.setLayout(pvbxLayout);

wgt.show();

return app.exec();
}


(. 8.2). , , Microsoft Internet
Explorer. Start () Windows 7
. , setMenuO
.
(. 11).

Iteml
Item2
Suit

. 8.2.

8.2 and pmnu.


addActionO (. 31). Quit ()
quit ( ) ,
, .
setMenu().

8.2. main.cpp

#include <QtWidgets>

int main (int argc, char** argv)


{
QApplication app(argc, argv);

QPushButton cmd("Menu");
QMenu* pmnu = new QMenu(&cmd);
pmnu->addAction("Iteml");
pmnu->addAction("Item2");
pmnu->addAction("&Quit", &app, SLOT(quit()));

cmd.setMenu(pmnu);
cmd.show();

return app.exec();
160 II.

,
. ,
. QCheckBox
QCheckBox.

, QListwidget (.
11 12).

. .
<>, .
,
, - (toggle button). , ,
(. 8.3).
Properties ()
Windows , .

. 8.3.

8.3 : pchkNormal pchkTristate.


Normal Check Box ( ) setCheckedO
true. Tristate Check Box ( )
, true
setTristate ( ) . setCheckState ( )
Qt::PartiallyChecked .

8.3. main.cpp

#include <QtWidgets>

int main(int argc, char** argv)


{
QApplication app(argc, argv);

QWidget wgt;
QCheckBox* pchkNormal = new QCheckBox("SNormal Check Box");
pchkNormal->setChecked(true);

QCheckBox* pchkTristate = new QCheckBox("STristate Check Box");


pchkTristate->setTristate(true);
pchkTristate->setCheckState(Qt::PartiallyChecked);
8. , 161

//Layout setup
QVBoxLayout* pvbxLayout = new QVBoxLayout;
pvbxLayout->addWidget(pchkNormal);
pvbxLayout->addWidget(pchkTristate);
wgt.setLayout(pvbxLayout);

wgt.show();

return app.exec();
}

radiobutton
,
.
, , .
(. 8.4),
: (on) (off).
<>, .
QRadioButton QRadioButton.

. 8.4.

, ,
,
. , ,
QGroupBox.

,
. &
.


, ,
. ,
QComboBox (. 11).

8.4 gbx.
pradRed, pradGreen pradBlue (pradGreen)
setCheckedO true.
162 II.

gbx, QVBoxLayout
(. . 8.4).

8.4. main.cpp

#include <QtWidgets>

int main(int argc, char** argv)


{
QApplication apptargc, argv);

QGroupBox gbx(".Colors");

QRadioButton* pradRed = new QRadioButton("&Red");


QRadioButton* pradGreen = new QRadioButton C'&Green");
QRadioButton* pradBlue = new QRadioButton("&Blue");
pradGreen->setChecked(true);

//Layout setup
QVBoxLayout* pvbxLayout = new QVBoxLayout;
pvbxLayout->addWidget(pradRed);
pvbxLayout->addWidget(pradGreen);
pvbxLayout->addWidget(pradBlue);
gbx.setLayout(pvbxLayout);

gbx.show();

return app.exec();
)


, ,
.
. ,
. , , QRadioButton
.
QGroupBox ,
.
, ,
.
,
. QGroupBox QGroupBox.
, (. 8.5).
, Red () ,
. Light () , Exit
() . main.cpp
8.5.
8. , 163

. 8.5.

8.5. main.cpp

#include <QApplication>
#include "Buttons.h

int main (int argc, char** argv)


{
QApplication app(argc, argv);

Buttons buttons;
buttons.show();

return app.exec();
}

8.6, Buttons,
QGroupBox. m_pchk m_pradRed, m_pradGreen,
m pradBlue . ,
slotButtonClickedO.

8.6. Buttons.h

ipragma once

#include <QGroupBox>

class QCheckBox;
class QRadioButton;

// ===============================
class Buttons : public QGroupBox {
Q_OBJECT
private:
QCheckBox* m_pchk;
QRadioButton* m_pradRed;
QRadioButton* m_pradGreen;
QRadioButton* m_pradBlue;
public:
Buttons(QWidget* pwgt = 0);
164 II.

public slots:
void slotButtonClicked();
};

Buttons ( 8.7) setCheckable ( )


true , setChecked().
( pradRed, pradGreen pradBlue)
setChecked () true. clicked
slotButtonClicked().
Light () ( m pchk)
setChecked().
Exit () ( pcmd).
clicked ( ) quit ( )
.

QVBoxLayout.
slotButtonClicked () .

8.7. Buttons.cpp. Buttons

Buttons::Buttons(QWidget* pwgt/*= 0*/) : QGroupBox("QGroupBox", pwgt)


{
resize(100, 150);
setCheckable(true);
setChecked(true);

m_pradRed = new QRadioButton("&Red");


m_pradGreen = new QRadioButton("&Green");
m_pradBlue = new QRadioButton("&Blue");
m_pradGreen->setChecked(true);
connect(m_pradRed, SIGNAL(clicked()), SLOT(slotButtonClicked()));
connect(m_pradGreen, SIGNAL(clicked()), SLOT(slotButtonClicked()));
connect(m_pradBlue, SIGNAL(clicked()), SLOT(slotButtonClicked()));

m_pchk = new QCheckBox("&Light");


m_pchk->setChecked(true);
connect(m_pchk, SIGNAL(clicked()), SLOT(slotButtonClicked()));

QPushButton* pcmd = new QPushButton("&Exit");


connect(pcmd, SIGNAL(clicked()), qApp, SLOT(quit()));

//Layout setup
QVBoxLayout* pvbxLayout = new QVBoxLayout;
pvbxLayout->addWidget(m_pradRed);
pvbxLayout->addWidget(m_pradGreen);
pvbxLayout->addWidget(m_pradBlue);
pvbxLayout->addWidget(m_pchk);
8. , 165

pvbxLayout->addWidget(pcmd);
setLayout(pvbxLayout);

slotButtonClicked();
}

8.8 siotButtonClickedf),
Light ()
nLight, . if
- isChecked ( ) .
, Qwidget::backgroundRoie()
QPaiette::setcoior ( )
Qwidget::setPaiette ( ) . 13.

8.8. Buttons.cpp. slotButtonClicked ()

void Buttons::slotButtonClicked()
{
QPaiette pal = paletted;
int nLight = m_pchk->isChecked() ? 150 : 80;
if(m_pradRed->isChecked()) {
pal.setColor(backgroundRole(), QColor(Qt::red).light(nLight));
}
else if(m_pradGreen->isChecked()) {
pal.setColor(backgroundRole(), QColor(Qt::green).light(nLight));

else (
pal.setColor(backgroundRole(), QColor(Qt::blue).light(nLight));
}
setPaiette(pal);

, QAbstractButton: ,
.
.
pressed ( ) , released ( ) .
clickedo, , .
, .
. ,
.
,
.
--.

.

.
9

, - IBM

, , , ,
, , ,
, () ,
.

QAbstractSlider
: (QSlider),
(QScrollBar) (QDial) (. . 5.1).
.
QAbstractSlider.
,
sliderChange ( ) , .


, QAbstractSlider,
, .
setOrientation () ,

Qt: : Horizontal, Qt: : Vertical.


setRangeO.
( ),
( ).
setMinimumO setMaximum ( ) . ,
1 10, :
psld->setRange (1, 10) ;
:
psld->setMinimum(l) ;
psld->setMaximum(10) ;
9. 167


setSingleStep ( ) , , ,
,
.
setPageStep ( ) . ,
, ,
<Page Up>, <Page Down>.


- ,
setvalue ( ) . value ( ).
sliderMoved(int)
.
valueChanged ( ) sliderMoved(int)
.
setTracking ( ) .
false, , valueChanged ()
.
,
, sliderPressedO
sliderReleased ().


. QSlider QSlider.
QSlider , () .
.
. ,
setTickPosition ( ) , . 9.1.

9.1. TickPosition QSlider

NoTicks

TicksAbove

TicksBelow

TicksBothSides
I I 1 I 1 1
168 II.

setTickinterval ( ) .
,
.
( 9.1) . ,
. 9.1, ,
.

I Slide I I
. 9.1. ,

9.1. main.cpp

tinclude <QtWidgets>

int main (int argc, char** argv)


{
QApplication app(argc, argv);

QWidget wgt;
QSlider* psld = new QSlider(Qt::Horizontal);
QLabel* plbl = new QLabel("3");

psld->setRange(0, 9);
psld->setPageStep(2);
psld->setValue(3);
psld->setTickInterval(2);
psld->setTickPosition(QSlider::TicksBelow);
QObject::connect(psld, SIGNAL(valueChanged(int)),
plbl, SLOT(setNum(int))
);

//Layout setup
QHBoxLayout* phbxLayout = new QHBoxLayout;
phbxLayout->addWidget(psld);
phbxLayout->addWidget(plbl);
wgt.setLayout(phbxLayout );

wgt.show();

return app.exec();
}

9.1 ( psld) ( plbl).


setRange ( )
0 9. 2 setPageStep ( ).
setvalue ( ) ,
, .
9. 169

, ,
.
setvalueO 3, ,
.
,
setTickinterval ( ) 2. setTickmarks ( )
. connect () valueChanged(int)
setNum(int).

wgt.




. ,
,
. ,
.
, .
QScrollBar .
QscrollBar ,
QAbstractSlider.
.
QAbstractScrollArea. ,
QscrollBar, ,
,
QAbstractScrollArea.
, QscrollBar,
(. 9.2).
,
.
. ,
.
( 9.2), . 9.3,
. , ,
.

i rrrI
j Scroll here i

Left edge
Right edge

Page left
Page right
Scroll left
Scroll right

. 9.2. . 9.3. ,

170 II.

9.2. main.cpp

#include <QtWidgets>

int main (int argc, char** argv)


{
QApplication app(argc, argv);

QWidget wgt;
QLCDNumber* pled = new QLCDNumber(4);
QScrollBar* phsb = new QScrollBar(Qt: horizontal);

QObject::connect(phsb, SIGNAL(valueChanged(int)),
pled, SLOT(display(int ))
);

//Layout setup
QVBoxLayout* pvbxLayout = new QVBoxLayout;
pvbxLayout->addWidget(pled);
pvbxLayout->addWidget(phsb);
wgt.setLayout(pvbxLayout );

wgt.resize(250, 150);
wgt.show();

return app.exec();
}

9.2 ( pled)
( phsb). vaiueChangedO
display ( ) ,
, connect ( ) .
wgt
QVBoxLayout.

QDial QDial.
,
.
. ,
, .
setwrapping ( ) .
setNotchTarget ( ) ,
, setNotchesVisible(), .
( 9.3), . 9.4,
.
.
9. 171

9.3. main.cpp

#include <QtWidgets>

int main (int argc, char** argv)


{
QApplication app(argc, argv);

QWidget wgt;
QDial* pdia = new QDial;
QProgressBar* pprb = new QProgressBar;

pdia->setRange(0, 100);
pdia->setNotchTarget(5);
pdia->setNotchesVisible(true);
QObject::connect(pdia, SIGNAL(valueChanged(int) ),
pprb, SLOT(setValue(int))
);

//Layout setup
QVBoxLayout* pvbxLayout = new QVBoxLayout;
pvbxLayout->addWidget(pdia);
pvbxLayout->addWidget(pprb);
wgt.setLayout(pvbxLayout );

wgt.resize(180, 200);
wgt.show();

return app.exec();
}

9.3 (
pdia) ( pprb).
setRangeO
0 100. setNotchTarget() ,
5, setNotchesvisible() ,
true.

. 9.4. ,

valueChanged(int) connect()
setProgress(int).

QVBoxLayout .
172 II.

,
. QAbstractsiider,
, .
,
, . . ,

.
,
.
.
, ,

.
10

, , , ,
,
.


.
(drag & drop),
. ,
.


. QLineEdit
QLineEdit.
,
, .
QTextEdit.
, , text().
, textChanged ( ) . ,
, , ,
textEdited ( ) . returnPressed ( )
<Enter>. setReadOnly ( ) true
,
, .
setText ().

, I LineEdit
)
setEchoMode ( ) Password.
, *.
Top Secret
( 10.1), . 10.1,
, Text:
. test
.
Password :

. 10.1.
174 II.

10.1. main.cpp

#include <QtWidgets>

int main (int argc, char** argv)


{
QApplication app(argc, argv);
QWidget wgt;

QLabel* plblDisplay = new QLabel;


plblDisplay->setFrameStyle(QFrame::Box | QFrame::Raised);
plblDisplay->setLineWidth(2);
plblDisplay->setFixedHeight(50);

QLabel* plblText = new QLabel("&Text:");


QLineEdit* ptxt = new QLineEdit;
plblText->setBuddy(ptxt);
QObject::connect(ptxt, SIGNAL(textChanged(const QStrings)),
plblDisplay, SLOT(setText(const QStrings))
);

QLabel* plblPassword = new QLabel C'&Password:");


QLineEdit* ptxtPassword = new QLineEdit;
plblPassword->setBuddy(ptxtPassword);
ptxtPassword->setEchoMode(QLineEdit::Password);
QObject::connect(ptxtPassword, SIGNAL(textChanged(const QStrings)),
plblDisplay, SLOT(setText(const QStrings))
);

//Layout setup
QVBoxLayout* pvbxLayout = new QVBoxLayout;
pvbxLayout->addWidget(plblDisplay);
pvbxLayout->addWidget(plblText);
pvbxLayout->addWidget(ptxt);
pvbxLayout->addWidget(plblPassword);
pvbxLayout->addWidget(ptxtPassword);
wgt.setLayout(pvbxLayout );

wgt.show();

return app.exec();
}

10.1 ( plblDisplay). setFrameO


, a setLinewidth() .
setFixedHeight(). , plblText plblPassword,
setBuddy().
textChanged() setText() plblDisplay
.
QVBoxLayout.
10. 175

setMaxLength ( ) ,
, .
maxLength ( ).
QLineEdit :
( ) ;

cut ( ) ;
paste ( ) ( ), .
undo ( ) , redo ( )
.
isUndoAvailable () isRedoAvailable () ,
.
- (validator),
. .


QTextEdit ,
HTML. QAbstractScrollArea,
,
.


,
QTextEdit QPiaintTextEdit. QPiaintTextEdit
RTF (Rich Text Format, ),
, .

QTextEdit :
setReadOnly ( ) ;
text ( ) .
:
setPlainText ( ) ;
setHtml ( ) HTML;
(), cut () paste () (,
);
selectAll ( ) deselect ( ) ;
clear ( ) .
:
textchanged ( ) ;
selectionChanged ( ) .
QTextCursor,
QTextEdit. QTextCursor
176 II.

, .
QTextCursor QTextEdit :: textCursor ( ) .
QTextEdit QText Document,
QTextEdit : : document ( ) .
QTextEdit : : setDocument ( ) . QTextDocument
undo() ( ) redo() ( ).
undo () redo () undoAvailable (bool) redoAvailable (bool) ,
( ) .
QTextDocument, QTextEdit.
QTextEdit.
QTextEdit
QTextDocument. , , QTextEdit
HTML, .
setHtml ( ) ,
, HTML, insertHtml ( ) .
, QTextEdit
, QTextDocument.

insertPlainText ( ) . append ( )
setPlainText ( )
, ,
undo ( ) ,
. find()
.

QTextEditor QSyntaxHighlighter -
.

zoomin ( ) zoomOut ( )
, .

HTML, , ,
QLabel (. 7).

( 10.2) HTML- (. 10.2).


.

10.2. main.cpp

#include <QtWidgets>

int main(int argc, char** argv)


{
QApplication app(argc, argv);
QTextEdit txt;

txt.setHtml ("<HTML>M
"<BODY BGCOLOR=MAGENTA>
"<CENTER><IMG SRC=\":/MetroGnome.png\"></CENTER>"
10. 177

"<2><CENTER>Gnome Poem 3: Magic Magic</CENTERX/H2>"


"<H3XCENTER>(http://ynstyn.tripod.com)</CENTERXH3>"
"<FONT COLOR=BLUE>"
"<p ALIGN=\"center\">
"<I>"
"Magic! Magic!<BR>"
"Are you here?<BR>"
"Abra-ca-dabra!<BR>"
"We appear.<BRXBR>"
"Magic! Magic!<BR>"
"Gnomes are we.<BR>"
"Magic gnomes<BR>"
"Of mystery.<BR>"
I I

</p>
"</FONT>"
"</BODY>"
"</HTML>"
);
txt.resize(320, 250);
txt.show();

return app.exec();
)

10.2
txt. setHtmio
QTextEdit HTML.

Gnome Poem 3: Magic Magic


(http:/ /ynstyn.tripod.com)

Magic! Magic!
Are you here?
Abra-ca-dabra!
We appear.

Magic! Magic!
Gnomes are ive.
Magic gnomes
. 10.2. ,
Of mystery.
HTML-
178 II.


QTextDocumentwriter
QTextDocument: PlainText ( ), HTML ODF (OpenDocument Format,
).
, OpenOffice.org LibreOffice.
, setFormat ( ) .
, ODF- (
10.3).

10.3. ODF

QTextEdit* ptxt = new QTextEdit("This is a <b>TEST</b>");


QTextDocumentwriter writer;
writer.setFormat("odf");
writer.setFileName("output.odf");
writer.write(ptxt->document());

10.3 ( ptxt)
(writer). setFormat
ODF setFileName . write
,
QTextDocument.
PDF QTextDocumentwriter ,
QPrinter. ,
( 10.4).

10.4. PDF

QTextEdit* ptxt = new QTextEdit("This is a <b>TEST</b>");


QPrinter printer(QPrinter::HighResolution);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setOutputFileName("output.pdf");
ptxt->document()->print(sprinter);

10.4 ( ptxt),
(printer),
HighResolution.
setOutputFormat , PdfFormat,
NativeFormat PostScriptFormat
PostScript . setOutputFileName
QTextDocument ,
.
.

(syntax highlighting)

. QTextEdit
10. 179

QSyntaxHighlighter
highlightBlock ().
:
/virtual*/ void MyHighlighter::highlightBlock(const QStrings str)
(
for (int i = 0; i < str.length(); ++i) {
if (str.at(i).isNumber()) {
setFormat(i, 1, Qt::red);
}

, highlightBlock!) .
setFormatO ,
( 1),
( Qt::red).
(QFont, . 20).
QTextEdit,
QTextDocument. :
MyHighlighter* pHighlighter = new MyHighlighter(ptxt->document());

,
QTextDocument, ,
QTextEdit, ,
QTextDocument. , , QTextBrowser, QTextFrame,
QTextTabie, QGraphicsTextitem
(. 21) .
, QSyntaxHighlighter,
,
C++ Borland (. 10.3).
( 10.5) txt QTextEdit
. fnt
setDefaultFont () .

SyntaxHighiighter
.
pal, , () (
) . show ( )
resize(). SyntaxHighiighter. ,
open ( )
. readAllo
setPlainText().

10.5. main.

#include <QtWidgets>
#include "SyntaxHighiighter.h"

int main (int argc, char** argv)


180 II.

{
QApplication app(argc, argv);
QTextEdit txt;

QFont fnt("Lucida Console", 9, QFont::Normal);


txt.document()->setDefaultFont(fnt);

new SyntaxHighlighter(txt.document());

QPalette pal = txt.palette();


pal.setColor(QPalette::Base, Qt::darkBlue);
pal.setColor(QPalette::Text, Qt::yellow);
txt.setPalette(pal);

txt.show();
txt.resize(640, 480);

QFile file(":/SyntaxHighlighter.cpp");
file.open(QFile::Readonly);
txt.setPlainText(QLatinlString(file.readAll()));

return app.exec();
}

. 10.3.
10. 181

( .6) SyntaxHighlighter
QSyntaxHighlighter. NormalState, InsideCStyleComment
insidecstring, .
highlightBlockO,
. getKeyword {) ,
, C++
Qt.

10.6. SyntaxHighlighter.h

tpragma once

#include <QSyntaxHighlighter>

class QTextDocument;

// ===============================================================
class SyntaxHighlighter: public QSyntaxHighlighter {
Q_OBJECT
private:
QStringList m_lstKeywords;
protected:
enum { NormalState = -1, InsideCStyleComment, InsideCString };

virtual void highlightBlock(const QStrings);

QString getKeyword(int i, const QStrings str) const;

public:
SyntaxHighlighter(QTextDocument* parent = 0);
);

m lstKeywords
( 10.7).

10.7. SyntaxHighlighter.cpp. SyntaxHighlighter()

SyntaxHighlighter::SyntaxHighlighter(QTextDocument* parent/*= 0*/)


: QSyntaxHighlighter(parent)
{
m_lstKeywords
"foreach" "bool" "int" "void" "double"
"float" "char" "delete" "class" "const"
"virtual" "mutable" "this" "struct" "union"
"throw" "for" "if" "else" "false"
"namespace" "switch" "case" "public" "private
"protected" "new" "return" "using" "true"
VV V ">"
182 II.


" VV
_
|it |ii
it
VV
I it
* VV \
"!" it



VV
" . II "&" "emit" "connect" "SIGNAL"
1" "SLOT" "slots" "signals" r
}

highlightBlock ( ) ,
. highlightBlock ( )
, .
:
Normaistate , ,
(. 10.5);

insideCString , .
Qt : : cyan;
InsideCStyleComment ,
/*...*/. - Qt : :darkGray.

nState ( 10.8),
previousBlockstate ( ) .
insideCStyleCornment InsideCString.
*/ , ,
nState Normaistate - ,
i , .
InsideCString
( '), ,
\, , \",
,
. ,
,
.
if ,
, .
, , ,
. //,
, #, (
QString: : isNumber ( ) ), C++ Qt.
( 10.9) getKeyword ( ) .
, .
i ,
.
InsideCStyleComment InsideCString
/* " .
, InsideCStyleComment
insideCString,
.
setCurrentState ( ) .
10. 183

10.8. SyntaxHighlighter.cpp. highlightBlock ()

/virtual*/ void SyntaxHighlighter::highlightBlock(const QStrings str)


{
int nState = previousBlockState();
int nStart = 0;
for (int i = 0; i < str.length(); ++i) {
if (nState == InsideCStyleComment) {
if (str.mid(i, 2) == "*/") {
nState = NormalState;
setFormat(nStart, i nStart + 2, Qt::darkGray);
i++;
}
}
else if (nState == InsideCString) {
if (str.mid(i, 1) == "V" II str.mid(i, 1) == "V") {
if (str.mid(i - 1, 2) != "\\\"n
&& str.mid(i - 1, 2) != "\\\"'
) {
nState = NormalState;
setFormat(nStart, i
nStart + 1, Qt::cyan);
}
}
}
else {
if (str.midfi, 2) == "//") {
setFormat(i, str.length!) i, Qt::darkGray);
break;
}
else if (str.mid(i, 1) == "#") {
setFormat(i, str.length() i, Qt::green);
break;
}
else if (str.at(i).isNumber()) {
setFormat(i, 1, Qt::cyan);
}
else if (str.midfi, 2) == "/*") {
nStart = i;
nState = InsideCStyleComment;
}
else if (str.mid(i, 1) == I I str.midfi, 1) == {
nStart = i;
nState = InsideCString;
}
else {
QString strKeyword = getKeyword(i, str);
if (!strKeyword.isEmpty()) {
setFormat(i, strKeyword.length(), Qt::white);
184 II.

i += strKeyword.length {) 1;
}
}
}
if (nState == InsideCStyleComment) {
setFormat(nStart, str.length)) nStart, Qt: idarkGray);
}
if (nState == InsideCString) {
setFormat(nStart, str.length() nStart, Qt::cyan);
}
setCurrentBlockState(nState);

getKeywordO ( 10.9)
C++ Qt. m_lstKeyword
foreach
.
strTemp, (break),
.

10.9. SyntaxHighlighter.cpp. getKeywordO

QString SyntaxHighlighter::getKeyword(int nPos, const QStrings str) const


{
QString strTemp =

foreach (QString strKeyword, m_lstKeywords) {


if (str.mid(nPos, strKeyword.length()) == strKeyword) {
strTemp = strKeyword;
break;

return strTemp;
}

,
,
. , , ,
, ,
, QSyntaxHighlighter.

?
QAbstractSpinBox

.
10. 185

(. . 5.1):
QSpinBox ;
QDateTimeEdit ;
QDoubleSpinBox , double.
,
, .
setwrapping ( ) true.
stepupo stepDown(),
.
setspecialValueText ( ) ,
, :
pspb->setSpecialValueText("default");

QSpinBox .
,
setRange ( ) , .
setvalue( ) , value ( ) .
valueChanged( ) : int,
const QStrings.

setPrefixO setSuffix().
, ,
:
pspb->setPrefix("(");
pspb->setSuffix(")");

+ () - (),
setButtonSymbols ( ) PlusMinus.
( 10.10)
1 100 (. 10.4).

. 10.4.
jl --
i

10.10 spb.
setRange (). setSuffixO
" " , setButtonSymbols ( ) ,
PlusMinus, +/-. setwrapping()
. ,
QWindowStyle.
186 II.

10.10. main.cpp

#include <QtWidgets>

int main (int argc, char** argv)


{
QApplication app(argc, argv);
QSpinBox spb;

spb.setRange(1, 100);
spb.setSuffix(" MB");
spb.setButtonsymbols(QSpinBox::PlusMinus);
spb.setwrapping(true);
spb.show();
spb.resize(100, 30);

return app.exec();
}


,
.
dateTimeChangedO .
QDateTimeEdit QDateTime.
( 10.11)
, (. 10.5).

DateTittte&fit . 10.5.
0/6/2306 S:41:52 AM IS

10.11, QDataTimeEdit
,
QDateTime::currentDateTime ( ) . show().

10.11. main.cpp

#include <QtWidgets>

int main (int argc, char** argv)


{
QApplication app(argc, argv);
QDateTimeEdit dateTimeEdit(QDateTime::currentDateTime());
dateTimeEdit.show();
return app.exec();
}
10. 187


QValidator ( )
. QValidator
setvalidator ( ) , QComboBox QLineEdit.
Qintvaiidator QDoubleValidator.
, QValidator
validate ( ) , .
:
QValidator::invalid ;
QValidator::intermediate
. , 50 1 00,
I ;
QValidator: Acceptable .
,
(. .6). ,
, .

. 10.6. ,
,

( 10.12) Namevalidator
QValidator. validated,
.
(. 4), ,
0 9. if QString::contains d
. ,
, invalid, ,
, Acceptable .

10.12. NameValidator. main.cpp

class Namevalidator : public QValidator {


public:
Namevalidator(QObject* parent) : QValidator(parent)
{
}

virtual State validate(QStrings str, int& pos) const


t
QRegExp rxp = QRegExpC[0-9]");
if (str.contains(rxp)) {
return Invalid;
}
return Acceptable;
188 II.

10.13 ( piblText),
( ptxt) ( pnamevalidator).
setvalidator ()
( ptxt),
setBuddy().

10.13. . main.cpp

int main (int argc, char** argv)


{
QApplication app(argc, argv);
QWidget wgt;

QLabel* piblText =
new QLabel("&Name (The digits will not be accepted!):");

QLineEdit* ptxt = new QLineEdit;

NameValidator* pnamevalidator = new NameValidator(ptxt);


ptxt->setValidator(pnamevalidator);
plblText->setBuddy(ptxt);

//Layout setup
QVBoxLayout* pvbxLayout = new QVBoxLayout;
pvbxLayout->addWidget(piblText);
pvbxLayout->addWidget(ptxt);
wgt.setLayout(pvbxLayout);
wgt.show();

return app.exec();
}

,
.
,
(drag & drop).
QLineEdit .
QTextEdit.
QAbstractScrollArea, ,
. QTextDocumentwriter
ODF, HTML, QPrinter
PDF-.
(QSpinBox) .
, .
QComboBox (. 11)
QLineEdit setvalidator().
11

,
.

.


, . ,

, . ,
QListwidget, QTreeWidget QTableWidget
-, 12.
, ,
,
. -,
, ,
. ...


QListwidget ,
.
. , addltem().
:
QListwidget item. ,
clear () .
QListwidget item .
, QListwidget : : additem( ) .
, QListwidget item ,
.
clone ( ) .


,
QStringList, (. 4), insertitems () .
insertitemO
190 II.

. insert item ()
QListwidgetitem. insertitemO
additemO ,
.
,
QListwidgetitem::seticon ( ) .
,
, . QListwidget
setitemwidget ( ) itemwidget ( ) . setitemwidget ()
,
.
, ,
itemwidget ( ) .

!

.

( 11.1) ,
(. 11.1).
11.1 lwg.
seticonSizeO
. 1st
.
foreach, .
seticon ()
.

. 11.1.

11.1. main.cpp

#include <QtWidgets>

int main(int argc, char** argv)


{
QApplication app(argc, argv);
QStringList 1st;
QListwidget lwg;
QListwidgetitem* pitern = 0;

lwg.setlconSize(QSize(48, 48));
1st "Linux" "Windows" "MacOSX "Android";
foreach(QString str, 1st) {
pitem = new QListwidgetitem(str, &lwg);
11. 191

pitem->setIcon(QPixmap(":/" + str + ".jpg"));


}
lwg.resize(125, 175);
lwg.show();

return app.exec();
}


, , QListwidget::
currentitemO , .
, selecteditems( ) ,
. ,
setSelectionMode(),
QAbstractltemView, QAbstractltemView::MultiSelection.
, ,
QAbstractltemView::NoSelection,
QAbstractltem::SingleSelection.
itemClickedO .
itemDoubleClickedO
QListwidgetitem*.
itemSelectionChanged().


,
QListwidgetitem: :setFlags ( )
Qt : : itemisEditable . :
pitem->setFlags(Qt::ItemisEditable | Qt::ItemlsEnabled);

<F2>. QListwidget
itemChanged(QListwidgetitem*) itemRenamed(QListwidgetitem* ) .


(
), ,
(drag & drop).
( 11 .2)
(. 11 .2).
11 .2 lwg. setSelectionMode ( )
. setviewMode()
QListview::iconMode .
1st, . lwg
foreach. setFlags()
, (Qt: iitemisEnabled),
(Qt::itemisSelectable), (Qt::ItemisEditable)
(Qt::ItemlsDragEnabled).
192 II.

. 11.2.

QListwidget
. setFlow(),
QListview.
QListview::TopToBottom, .

11.2. main.cpp

#include <QtWidgets>

int main(int argc, char** argv)


{
QApplication app(argc, argv);
QListwidget lwg;
QListwidgetItem* pitem = 0;
QStringList 1st;

lwg.setlconSize(QSize(48, 48));
lwg.setSelectionMode(QAbstractltemView::MultiSelection);
lwg.setViewMode(QListview::IconMode);
1st "Linux" "Windows" "MacOSX "Android";
foreach(QString str, 1st) {
pitem = new QListWidgetItem(str, &lwg);
pitem->setIcon(QPixmap(":/" + str + ".jpg"));
pitem->setFlags(Qt::ItemlsEnabled I Qt::ItemlsSelectable I
Qt::ItemlsEditable I Qt::ItemlsDragEnabled);

}
lwg.resize(150, 150);
lwg.show();

return app.exec();
}


sortitemsO.
Qt::AscendingOrder
, Qt::DescendingOrder . ,
, , .
, -
11. 193

, QListwidgetitem
operator< ( ).


QTreeWidget
.
. ,
, .
setitemwidget () .
,
. , ,
.
, ,
, .
,
. , ( 1 1.3) (
pwti) Qt::itemisUserCheckable
.
. . 11.3
.

11.3.

QTreeWidget Item* ptwi = new QTreeWidgetltem(pTreeView);


ptwi->setFlags(ptwiTemp->flags () I Qt::ItemisUserCheckable);
ptwi->setCheckState (0, Qt ::Checked);
ptwi->setText (0, "Checkable Item");

I
Checkable Item
___
Checkable Item
Si Checkable Item
l l rf".l It.
. 11.3.

, ,
,
Qt::Checked. :
if (ptwi->checkState (0) == Qt::Checked) {
//This item is checked
}

QTreeWidgetitem
. QTreeWidgetitem
clone ( ) .
addChildren ( ) insertChildren ( ) .
,
QTreeWidgetitem::set icon () ,
QTreeWidgetitem::setText ( ) .
.
194 II.

. . 1 1.4 .
Local Disk(C)
().

TreeWidget
Folders Used Space

* *+ Local Disk(C)
tJ) Directory*} 9MB
. 11.4.
Directory# SMB

Directory? 7MB
Director 6 6MB
Directory5 SMB
Directory4 4MB
DirectoryS SMB

(, Windows)
QTreewidgetitem .
1 1.4 twg. 1st
. setHeaderLabelst) Folders ()
Used Space ( ). (
ptwgitem) twg.
.
20 . setText ( )
, seticont) .
setitemExpandedo ptwgitem
.

11.4. main.cpp

tinclude <QtWidgets>

int main(int argc, char** argv)


{
QApplication app(argc, argv);
QTreeWidget twg;
QStringList 1st;

1st "Folders" "Used Space";


twg.setHeaderLabels(1st);
twg.setSortingEnabled(true);

QTreewidgetitem* ptwgitem = new QTreewidgetitem(&twg);


ptwgItem->setText(0, "Local Disk(C)");
ptwgItem->setIcon(0, QPixmap(":/drive.bmp"));

QTreewidgetitem* ptwgltemDir = 0;
for (int i = 1; i < 20; ++i) {
ptwgltemDir = new QTreewidgetitem(ptwgitem);
ptwgItemDir->setText(0, "Directory" + QString::number(i));
ptwgItemDir->setText(1, QString::number(i) + "MB");
11. 195

ptwgItemDir->setIcon(0, QPixmap(":/folder.bmp"));
}
twg.setltemExpanded(ptwgltem, true);
twg.resize(250, 110);
twg.show();

return app.exec();
}
, ,
.
.
, setSortingEnabledO .
true, false.

. , setSelectionMode ()
QAbstractltemView QAbstractltemView::MultiSelection,
.
Qtreewidget, ,
:
QTreeWidgetltemlterator it(&twg, QTreeWidgetltemlterator::11);
while (*(++it)) {
qDebugO (*it)->text(0);
}

,
. ,
, .
QTreeWidgetltemlterator::All,
. , ,
QTreeWidgetltemlterator: :Selected.
, .
QTreeWidget :
;
itemSelectionChanged ( )
itemClicked(QTreeWidgetltem*, int) ;
itemDoubleClicked(QTreeWidgetltem*, int) ;
itemActivated(QTreeWidgetltem*, int) ,
<Enter> . ,
<Enter> ,
.
,
.
QTreewidget (drag & drop).
setFlagsO ,
Qt::itemisDragEnabled, ,
. :
pitem->setFlags(Qt::ItemlsDragEnabled | Qt::ItemlsEnabled);
196 II.

. ,
setFlags Qt: : itemisEditable (
!).


QListwidget,
sortitems ( ) ,
.
QTreewidgetitem operator<().
, 1 1.5.

11.5. QTreewidgetitem: :operator<()

bool MyTreeWidgetltem::operator(const QTreeWidgetltems ptwiOther)


{
bool bRet = false;
int nColumn = treeWidget()->sortColumn();
if (nColumn == 0) {
QString strFormat = "dd.MM.yyyy";
bRet = QDate::fromString(text(nColumn))
< QDate::fromString(ptwi.text(nColumn));

return bRet;
)

11.5 , ( 0)
. sortcoiumnt) ,
,
QTreewidget. 0, QDate
.
( bRet).

QTablewidget .
QTablewidgetitem.
QTablewidget::setitem(). setitemO ,
.
. QTablewidgetitem::
setText ( ) ,

QTablewidgetitem::seticon(). ,
, .
QTablewidgetitem ,
. clone().
, , .
setCellWidget().
11. 197


, QLineEdit.
( 11.6) ,
(. 11.5). .

a TableWidget
_
First Second Third

First 0.0 I '1 0,2

Second 1.0 1.2


Third 2,0 2,1 2,2

. 11.5.

1 1.6 tbi. ,
, .
3 3. ( ),
, setHorizontalHeaderLabel()
setverticalHeaderLabel .
( ptwi).
. setitemO
, .


, , QListwidget
QTreeWidget.

11.6. main.cpp

#include <QtWidgets>

int main(int argc, char** argv)


{
const int n = 3;

QApplication app(argc, argv);


QTableWidget tbl(n, n);
QTableWidgetltem* ptwi = 0;
QStringList 1st;

1st "First" "Second" "Third";


tbl.setHorizontalHeaderLabels(1st);
tbl.setVerticalHeaderLabels(1st);

for (int i = 0; i < n; ++i) {


for (int j =0; j < n; ++j) {
ptwi = new QTableWidgetltem(QString("%1,%2").arg(i).arg(j));
198 II.

tbl.setltem(i, j, ptwi);

}
tbl.resize(370, 135);
tbl.show();

return app.exec();
}


QComboBox
.
QListwidget.
() ,
. ()
, ,
().
/ .
additemO. ,
QStringList addltems(). setDuplicatesEnabled(false),
, .
, clear ( ).
, , currentindex (),
. ,
.
Windows, ().
setEditable ( ) true.

editTextChanged(const QStrings), .
activatedO:
int ( ), const QStrings
( ). ,
,
currentindexChanged(), int const QStrings .
( 11.7) (. 11.6).
.
, 11.7, cbo.
1st .

ComboBox - I .
John V

Paul
George

. 11.6.
11. 199

additemst) . setEditablef)
true .


,
QComboBox QVaiidator (. 10).

11.7. main.cpp

#include <QtWidgets>

int main(int argc, char** argv)


{
QApplication app(argc, argv);
QComboBox cbo;
QStringList 1st;

1st "John" "Paul" "George" "Ringo";


cbo.addltems(1st);
cbo.setEditable(true);
cbo.show();

return app.exec();
}

, , ,
. ,
, .
. ,
.
,
, .
. ,
setTabEnabled ( ) false.
setcurrentindex( ) .
( 11.8) Linux, Windows, MacOSX
Android (. 11.7). ,
.

. 11.7.
200 II.

11.8 tab. addTabO


. ,
, ,
.

11.8. main.cpp

#include <QtWidgets>

int main(int argc, char** argv)


{
QApplication app(argc, argv);
QTabWidget tab;
QStringList 1st;

1st "Linux" "Windows" "MacOSX" "Android";


foreach(QString str, 1st) {
tab.addTab(new QLabel(str, stab), QPixmap(": + str + ".jpg"), str);
}
tab.resize(360, 100);
tab.show();

return app.exec();
}


QTooiBox , .
( ) .
additem().
, insertitemO .
, count ( ) . removeitem().
currentwidget(),
.
currentchanged(int),
.
( 11.9)
,
(. 1 1.8).
11.9 .
additemO
. ,
.
. .

. 11.8.
11. 201

11.9. main.cpp

#include <QtWidgets>

int main(int argc, char** argv)


{
QApplication app(argc, argv);
QToolBox tbx;
QStringList 1st;

1st "Linux" "Windows" "MacOSX" "Android";


foreach(QString str, 1st) {
tbx.addltern(new QLabel(str, &tbx), QPixmapC':/" + str + ".jpg"), str);
}
tbx.resize(100, 80);
tbx.show();

return app.exec();
}

, .
.
QListwidget, QTreeWidget QTableWidget
-, .
, , :
QListwidget .
( );
QTreeWidget ;
QTableWidget ,
;
QComboBox .
, ;
QTabwidget
, ;
QToolBox QTabwidget.
.
12

,
-
,
, .

- , 11,
. ,
. ,
, , . ., ,
, . ,
SQL-
. , ,
, , ,
.
Qt , , , , -
. , -
. , -,
Qt, ,
, , , .
:
.
-
,
. - ,
;
. ,
, .
, ,
, ,
;
.
, , - ,
.
;
. , ,
, . Qt
(. 45);
12. , - 203

. Qt SQL,
,
(. 41).


, . 12.1.

L 0*0 |
aomi *
Onowyl
) vm
&04 *



//


|Nsonway|
. 12.1.

,
. :

;

;

,
;
,
.

,
. ,
,
, :
. Qt-
204 II.

QAbstract11emModel (. 12.2). ,
, .
QAbstractitemModel ,
.
. , ,
, ,
, ,
. , , ,
. .
QAbstractitemModei ,
. 12.2. QAbstractListModei ,
QAbstractTableModel .

QObject

QAbstractitemModei

[ QFileSystemModel
QStandarditemModel

QAbstractListModei

| QStringListModel
. 12.2.
QAbstractProxyModel

[ QldentityProxyModel

] QSortFilterProxyModel |
QAbstractTableModel

QSqlQueryModel

CJSqJbibleModell
S QSqIRelationsI TableModeI

QStandarditemModel .
-, ,
,
.
QStringListModel QAbstractListModei,
, .
(QStringList) .
, ,
. .
:
QStringListModel model;
model.setStringList(QStringList() " "
" "
" "
>;
12. , - 205

QAbstractProxyModel ,
.
.
QSortFilterProxyModel.
.
QFileSystemModel .
, , (. 12.3)
(,
QAbstarctitemview). ,
:
, ,
.

. 12.3.

. 12.4,
QAbstactScrollArea, ,
,
, . QObject| QPaintOevice
L_
( QWidget

QComboBox,
QWidget. QComboBox
QFrame

QAbstractScrollArea
setModelO,
. QAbstactltemVlew |
QHeaderView

QAbstractitemView, QListView
, , ,
, TQListWidget
.
setEditTriggers ( ) ,
[ QUndoView
. |QTableView
[QTabieWidget ]
'[QT
QT reeView |
QTreeWidget
. 12.4.
( )
206 II.

:
NoEditTriggers ;
Doubleclicked ,
;
SelectedClicked ,
.
Qt , , :
QListview
.
( );
QTreeview .
;
QTableView .
, QHeaderView QAbstractitemView.
,
QTableView QTreeview .


, ,

. ,
.
, . ,
,
, , .
,
QitemSelectionModel (. 12.5). ,
, QAbstractitemView: :
select ionModel ( ) , QAbstractitemView: :
setSelectionModel ( ) .

|QObJect 1
1[ QitemSelectionModel 1
. 12.5. QitemSelectionModel

( 12.1), . 12.6,
.
.
12.1 ( model),
. .
( pTreeView, pListview pTableView) ,
setModel ( ) . (
QitemSelectionModel).
12. , - 207

I ll IS I

. 12.6.

( model).
setSeiectionModel ( ) .

.
QitemSelectionModel::selectedindexes( )
QitemSelectionModel: :select ( ) .
currentChanged(), selectionChangedO, currentColumnChanged()
currentRowChanged().

12.1. main.cpp.

#include <QtWidgets>

int main(int argc, char** argv)


{
QApplication app(argc, argv);
QWidget wgt;

QStringListModel model;
model.setStringList(QStringList() "Iteml" "Item2" "Item3");

QTreeView* pTreeView = new QTreeView;


pTreeView->setModel(smodel);

QListView* pListView = new QListView;


pListView->setModel(smodel);

QTableView* pTableView = new QTableView;


pTableView->setModel(smodel);

QitemSelectionModel selection(smodel);
pTreeView->setSelectionModel(sselection);
pListView->setSelectionModel(sselection);
pTableView->setSelectionModel(sselection);

//Layout setup
QHBoxLayout* phbxLayout = new QHBoxLayout;
phbxLayout->addWidget(pTreeView);
phbxLayout->addWidget(pListView);
208 II.

phbxLayout->addWidget(pTableView);
wgt.setLayout(phbxLayout );

wgt.show();

return app.exec();
}


.
.
( ).
Qt QStyleditemDelegate (. 12.7),

, .
,
.
QAbstractltemDelegate, QStyleditemDelegate.

QObject I
_ SimpleDelegate 1 !1 igST
QAbstractltemDelegate j
tteml
QltemDelegate

fQSqlRelationaDe|egate|
. 12.7. . 12.8.

( 12.2), ,
() (. 12.8).
main(), 12.2, setitemDelegate ( )
( SimpleDelegate).
,
setAttribute ( )
Qt::WA_Hover.
SimpleDelegate paint .
QPainter.
QStyleOptionviewitem, QStyle.
,
. ,
,
option, ,
. QStyle::state MouseOver , ,
, ,
. 18.
,
createEditor(), setEditorData ( )
12. , - 209

setModelData(). createEditor() .
setEditorData() . setModelData()
.

12.2. main.cpp.

#include <QtWidgets>
// ======
---============
---
--- ---
============== ===========
class SimpleDelegate : public QStyledltemDelegate {
---
public:
SimpleDelegate(QObject* pobj = 0) : QStyledltemDelegate(pobj)
{
}

void paint(QPainter* pPainter,


const QStyleOptionViewItems option,
const QModellndexs index
) const
{
if (option.state & QStyle::State_MouseOver) {
QRect rect = option.rect;
QLinearGradient gradient(0, 0, rect.width(), rect.height());

gradient.setColorAt(0, Qt::white);
gradient.setColorAt(0.5, Qt::blue);
gradient.setColorAt(1, Qt::green);
pPainter->setBrush(gradient);
pPainter->drawRect(rect);
)
QStyledltemDelegate::paint(pPainter, option, index);

//
int mainfint argc, char *argv[])
{
QApplication app(argc, argv);
QStringListModel model;
model.setStringList(QStringList() "Iteml" "Item2" "Item3");

QListView listview;
listview.setModel(smodel);
listview.setltemDelegate(new SimpleDelegate(slistview));
listview.viewport()->setAttribute(Qt::WA_Hover);
listview.show();

app.exec();
210 II.


, , .
. ,
, ,
. ,

. .
,
, . ,
: , .
, , .
,
QModelindex. QModelindex ,
, , .
QAbstractitemModel::
data () . QAbstractitemModel::
index ( ) , . ,
(2, 5), :
QModelindex index = pModel->index(2, 5, QModelindex());
QVariant value = pModel->data(index);
,
(2, 5). index ( ) (invalid index).
,
QModelindex::isValid()


QModelindex data , ,
, ,
.


. , ,
.
QStandarditemModel (. 12.9).

_ HierarchicalMcdel 1|43>1 i
1 2 3
iteml
item 2
0 item3

1,0
0.1
1,1
0.2
1,2
2,0 2.1 2,2
3,0 3,1 3.2
0 item
itemS

. 12.9.
12. , - 211

QStandarditemModel ( 12.3).
, setData ( )
. data().

12.3. main.cpp.

#include <QtWidgets>

int main(int argc, char** argv)


{
QApplication app(argc, argv);
QStandardlteinModel model(5, 3);

for (int nTopRow = 0; nTopRow < 5; ++nTopRow) {


QModellndex index = model.index(nTopRow, 0);
model.setData(index, "item" + QString::number(nTopRow + 1));

model.insertRows(0, 4, index);
model.insertColumns(0, 3, index);
for (int nRow = 0; nRow < 4; ++nRow) {
for (int nCol = 0; nCol < 3; ++nCol) {
QString strPos = QString("%1,%2").arg(nRow).arg(nCol);
model.setData(model.index(nRow, nCol, index), strPos);
}
}
}

QTreeView treeView;
treeView.setModel(smodel);
treeView.show();

return app.exec();
}

, 12.3, ,
.
index ( ) .
insertRows ()
insertColumns ( ) . setData ( )
.
,
, QStandarditemModel.
, Qt4
. ,
. ( 12.4), . 12.10,
QFileSystemModel
.
12.4
QFileSystemMode. ! ,
212 II.

1.
Name Size Type Date Modified >

1 : Drive

** : Drive 1/21/2007 6 44:53 AM



! - nH MinGW File Folder 1/21/2007 5 28:00 AM
| - r*t Program Files File Folder 1/20/2007 5 51:23 PM
| - Q Qt File Folder 1/21/2007 5 28:45 AM
| - Iri Users File Folder 1/21/2007 1 35:09 AM
! - Windows File Folder 1/20/2007 5 57:58 PM
E|] autoexec.bat 24 bytes bat File 4/21/2006 E 51:25 PM
] config.sys 1 Q bytes sys File 4/21/2006 E 51:25 PM
] ntsign_incr.txt 472 bytes txt File 5/19/2006 5 00:03 AM
. D: Drive 1/1/1970 1:00:00 AM
| m Qt4 File Folder 1/21/20076:14:44 PM
H Makefile 240 KB File 1/21/2007 6:15:48 PM

. 12.10.

,
QTreeView.

12.4. main.cpp.

# include <QtWidgets>

int main(int argc, char** argv)


{
QApplication app(argc, argv);
QFileSysteiniyiodel model;
QTreeView treeView;

.
model setRootPath (QDir : : rootPath ( ) ) ;
treeView. setModel (&model) ;
treeView . show ( ) ;

return app . exec ( ) ;


}

index ( ) .
: , , ,
. ,
(. 12.4) ,
:
QModellndex index .
= model index (QDir : : currentPath ());
treeView. setRoot Index (index) ;

setRootindexO ,

( 12.5), . 12.1 1.
12.5 12.4 ,
(spl) (
12. , - 213

pTableview). (model).
- .
,
, . ,

.
. ,
<Enter>
activated (), ,
setRootindex () . ,
, .
, Windows
. ,
.

. 12.11.

12.5. main.cpp. -

#include <QtWidgets>

int main(int argc, char** argv)


{
QApplication app(argc, argv);
QSplitter spl(Qt::Horizontal);
QFileSystemModel model;

model.setRootPath(QDir::rootPath());

QTreeView* pTreeView = new QTreeView;


pTreeView->setModel(smodel);

QTableView* pTableview = new QTableView;


pTableView->setModel(smodel);
214 II.

QObject::connect(pTreeView, SIGNAL(clicked(const QMode1Index&)),


pTableView, SLOT(setRootlndex(const QModellndexs))
);
QObject::connect(pTableView, SIGNAL(activated(const QModellndexs)),
pTreeView, SLOT(setCurrentlndex(const QModellndexs))
);
QObject::connect(pTableView, SIGNAL(activated(const QModellndexs)),
pTableView, SLOT(setRootlndex(const QModellndexs))
);

spl.addWidget(pTreeView);
spl.addWidget(pTableView);
spl.show();

return app.exec();
}


(QModelindex) , ,
.
, (QModelindex)
.
,
.
QAbstractitemModel : :data(), , ,
DisplayRoie. ,
data ( ) QVariant, .
, , ,
. - . ,
,
, .
.
:
DisplayRoie :
DecorationRole ;
FontRole ;
ToolTipRole (ToolTip);
whatThisRole ?;
TextColorRole ;
BackgroundColorRoie .
( 12.6) , ,
Qt: : DisplayRoie, Qt : : ToolTipRole Qt : : DecorationRole (. 12.12).
12.6
Qt: : DisplayRoie, Qt::
12. , - 215

ToolTipRole. Qt:: DecorationRole ,


".jpg.
, .



m
Linux Windows MacOSX Android
. 12.12.

ToolTip for Windows


_ j

12.6. main.cpp.

#include <QtWidgets>

int main(int argc, char** argv)


{
QApplication app(argc, argv);
QStringList 1st;
1st "Linux" "Windows" "MacOS" "OS2";
QStandardltemModel model(1st.size(), 1);
for (int i = 0; i < model.rowCount(); ++i) {
QModelIndex index = model.index(i, 0);
QString str = 1st.at(i);
model.setData(index, str, Qt::DisplayRole);
model.setData(index, "ToolTip for " + str, Qt::ToolTipRole);
model.setData(index, QIcon(str + ".jpg"), Qt::DecorationRole);
}

QListView listView;
listView.setViewMode(QListView::IconMode);
listView.setModel(smodel);
listView.show();

return app.exec();
}


,
QAbstractitemModel, .
(. . 12.2) ,
.
. , . 12.13
, .
12.7
. , setModel ( ) ,
.
216 II.

. 12.13.

12.7. main.cpp

#include <QtWidgets>
#include "IntListModel.h"

int main( int argc, char** argv ) {


QApplication app( argc, argv );
IntListModel model(QList<int>() 123 2341 32 5342 723);
QListView list;
list.setModel(smodel);
list.show();

QTableView table;
table.setModel(smodel);
table.show();

return app.exec();
}

12.8.
QAbstractListModel rowCountO data().
rowCount ( ) , data ( )
, QVariant.
headerData ( ) . ,
QTableView QTreeView.
, flags ( ) setData().

12.8. IntListModel.h

#pragma once

#include <QAbstractListModel>

,
/ =========================================

class IntListModel : public QAbstractListModel {


Q OBJECT
12. , - 217

private:
QList<int> m_list;

public:
IntListModel(const QList<int>& list, QObject* pobj = 0);

QVariant data(const QModellndexs index, int nRole) const;

bool setData(const QModellndexs index,


const QVariant& value,
int nRole

int rowCount(const QModellndexS parent = QModelIndex()) const;

QVariant headerData(int nSection,


Qt::Orientation orientation,
int nRole = Qt::DisplayRole
) const;

Qt::ItemFlags flags(const QModellndex sindex) const;


};

( 12.9)
m list
.

12.9. IntListModel.cpp.

IntListModel::IntListModel(const QList<int>& list, QObject* pobj/*=0*/)


: QAbstractListModel(pobj)
, m_list(list)
{
}


,
, . data()
( 12.10)
QVariant. .
, (Qt::DisplayRole)
(Qt::EditRole), , ,
, .
, , ,
QVariant ,
.

12.10. IntListModel.cpp. data()

QVariant IntListModel::data(const QModelIndex& index, int nRole) const


{
if (!index.isValidO ) {
218 II.

return QVariant();
}
return (nRole == Qt::DisplayRole || nRole == Qt::EditRole)
? m_list.at(index.row())
: QVariant();
}

setData ( ) : ,
( 12.11). isvalid().
, ,
(m list), replace () . ,
, .
value QVariant
QVariant::value<T>(), int (. 4).
QVariant::toint ( ) .
dataChanged ( ) , ,
. ( )
true , a false
.

12.11. IntListModel.cpp. setData ()

bool IntListModel::setData(const QModellndexs index,


const QVariant& value,
int nRole
)
{
if (index.isValid() && nRole == Qt::EditRole) {
m_list.replace(index.row(), value.value<int>());
emit dataChanged(index, index);
return true;
}
return false;

rowCountO, 12.12, .
,
(m_list).

12.12. IntListModel. rowCountO

int IntListModel::rowCount(const QModellndexs parent/*=QModelIndex()*/

return m_list.size();
}

headerDataO 12.13 ,
,
12. , - 219

.
,
( ).
, "Number",
.

12.13. IntListModel. headerDataO

QVariant IntListModel::headerData(int nSection,


Qt::Orientation orientation,
int nRole/*=DisplayRole*/
) const
{
if (nRole != Qt::DisplayRole) {
return QVariant();

return (orientation == Qt::Horizontal) ? QString("Number")


: QString::number(nSection);
}

, flags ()

Qt::itemisEditable. , (
12.14).

12.14. IntListModel. flags()

Qt::ItemFlags IntListModel::flags(const QModellndexs index) const


{
Qt::ItemFlags flags = QAbstractListModel::flags(index);
return index.isValid() ? (flags I Qt::ItemisEditable)

QAbstractTableModel
, QAbstractListModel. ,
QAbstractTableModel columnCount(),
.
( 12.15),
(. 12.14).
, 12.15, ,
12.7-12.14. ,
columnCount ( ) .
.
, . .
Qt: :EditRole setDataO, flags ()
Qt: : ItemisEditable. main()
200 200 .
220 II.

| \&\
"l TableModel
88 89 90 91 92
61 61,86 61,89 61.90 61,91 61,92

62 62,2-S 62,89 62,90 62,91 52,92


S3
62 63.88 63.89 63,90 63.91 63,92

64 64,88 64,89 64,90 64,91 64,52

65 65.88 65.89 65.90 65.91 55.92

66 66,88 66,89 66,90 56,91 66,92

67 67.88 67,89 67,90 67,91 67,92

4
u

. 12.14.

12.15. main.cpp.

# include <QtWidgets>

class TableModel : public QAbstractTableModel {


private :
int m_nRows;
int m_nColumns;
QHash<QModelIndex, QVariant> m_hash;

public:
//
TableModel (int nRows, int nColumns, QObject* pobj = 0)
: QAbstractTableModel (pobj )
, m_nRows (nRows)
, m_nColumns (nColumns)
{
}

//
QVariant data (const QModellndexs index, int nRole) const
{
if (! index.isValid () ) {
return QVariant ( ) ;
}
QString str =
QString ("%1, %2" ) .arg (index. row () + 1) .arg (index. column ( ) + 1);
return (nRole == Qt : : DisplayRole I I nRole == Qt : :EditRole)
? m_hash. value (index, QVariant (str) )
: QVariant ( ) ;
}
12. , - 221

//
bool setData(const QModellndexs index,
const QVariants value,
int nRole
)
{
if (index.isValidO && nRole == Qt::EditRole) {
m_hash[index] = value;
emit dataChanged(index, index);
return true;
}
return false;
}

//
int rowCount(const QModellndexs) const
{
return m_nRows;
}

//
int columnCount(const QModellndexs) const
{
return m_nColumns;
}

//
Qt::ItemFlags flags(const QModellndexs index) const
{
Qt::ItemFlags flags = QAbstractTableModel::flags(index);
return index.isValid() ? (flags | Qt::ItemlsEditable)
: flags;

};

//
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
TableModel model(200, 200);

QTableView tableView;
tableView.setModel(smodel);
tableView.show();

return app.exec();
}

QAbstractitemModel,
QAbstractTableModel.

QAbstractitemModel::index() QAbstractitemModel::parent().
222 II.

QAbstractltemModel::createlndex(),
.

(Proxy model)
, -
, .

, .
. ,
(. 12.15). -
, .

tnuHtPil DwcbayZ

. 12.15.

.
: ,
.
,
, .
, .
QSt Fi11ProxyMode1 ,
.
QSortFilterProxyModel::setFilterRegExp(),
QRegExp (. 4).
,
.
, .
.
( 12.16), . 12.16,
, .
, .
main , 12.16, QStringListModel,
.
QSortFilterProxyModel, setSourceMode ( )
. ,
, setFilterWildcard ( ) "*".


: ,
.
textChanged() setFilterWildcard()
12. , - 223

sortFilterProxyModei, ,
, .

QListview,
, .

. 12.16.

12.16. main.cpp.

#include <QtWidgets>

int main(int argc, char** argv)


{
QApplication app(argc, argv);
QWidget wgt;

QStringListModel model;
model.setStringList(QStringList() "Xandria"
"Epica"
"Therion"
"Evanescence"
"Nightwish"
);

QSortFilterProxyModel proxyModel;
proxyModel.setSourceModel(smodel);
proxyModel.setFilterWildcard("E*");

QListview* pListViewl = new QListview;


pListViewl->setModel(smodel);

QListview* pListView2 = new QListview;


pListView2->setModel( sproxyModel);

//Layout setup
QHBoxLayout* phbxLayout = new QHBoxLayout;
phbxLayout->addWidget(pListViewl);
phbxLayout->addWidget(pListView2);
wgt.setLayout(phbxLayout );

wgt.show();

return app.exec();
224 II.

-
11 - ,
: .
, . ( widget):
QListWidget, QTreeWidget QTableWidget.
-
QListview, QTreeview QTabieview (. . 12.4).
, , ,
. , -
(. 12.17),
, QAbstractltemView::model().

QListView QTreeView QTableView

"


fc
| i
* |1
QListWidget QTreeWidget QTableWidget
. 12.17. -

-
-,
,
- .
. 12.18 QListWidget ()
QListview () ,
. , ,
12.17.
12. , - 225

ListWidget
** ListView 75 1
Linux

--
Linux SS Windows
9 MacOSX
1 - Android
Windows

jjrjg MacOSX

Jpjf Android _
. 12.18.
1
12.17 11.1,
- QListwidget.
QListview.
( QListwidget),
model ( ) setModel()
listview. ,
selectionModel ( ) setSelectionModel().

12.17. main.cpp.

#include <QtWidgets>

int main(int argc, char** argv)


{
QApplication app(argc, argv);
QStringList 1st;
QListwidget lwg;
QListwidgetItem* pitem = 0;

lwg.setlconSize(QSize(48, 48));
1st "Linux" "Windows" "MacOS" "OS2";
foreach(QString str, 1st) {
pitem = new QListwidgetItem(str, &lwg);
pitem->setIcon(QPixmap(str + ".jpg"));
}
lwg.setWindowTitle("ListWidget");
lwg.show();

QListview listview;
listview.setModel(lwg.model());
listview.setSelectionModel(lwg.selectionModel());
listview.setWindowTitle("Listview");
listview.show();

return app.exec();
226 II.

-
, .
,
-, -
.
.

, .
,
.
.
.
,
.
- -
,
.
13



, ,
. ,
.

, ,
. ,

, . .

. 13.1.

,
palette ( ) QWidget.
QPalette,
(. 13.1).
: (Active), (Inactive) (Disabled).
(color roles),
. 13.1. (QBrush) (QColor).
228 II.


QPaiette , ,
.
, .

13.1. ColorRole QPaiette


WindowText , (. 18).
.
Text .
BrightText , WindowText.
Text.
ButtonText .
Highlight . -
HighlightedText . ,
Hightlight.
Window . -
Base .

Button , .

Link , .

LinkVisited , .

Light . ,
Button. (. 13.2)
Midlight . - (. . 13.2)
Dark . ,
Button. - (. . 13.2)
Mid . -
Shadow . (. . 13.2)

. 13.2 ,
, . 13. 1.

. 13.2.
13. 229

1 WidgetP alette
. 13.3. ,

13.1. . 13.3
.

13.1. main.cpp

#include <QtWidgets>

int main(int argc, char** argv)


{
QApplication app(argc, argv);
QSpinBox spb;

QPalette pal = spb.palette();

pal.setBrush(QPalette::Button, QBrush(Qt::red, Qt::Dense3Pattern));


pal.setColor(QPalette::ButtonText, Qt::blue);
pal.setColor(QPalette::Text, Qt::magenta);
pal.setColor(QPalette::Active, QPalette::Base, Qt::green);

spb.setPalette(pal);
spb.resize(50, 50);
spb.show();

app.setStyle(new QWindowsStyle);

return app.exec();
}

13.1 spb pal.


,
palette ( ) .
setBrush ( ) setColor ( ) .
, (. . 13.1). ,
, QPalette::Base
. , ,
( ).
setPalette () . ,
Windows ,
. 26.
13.1, setBrush ()
, . ,
, .
setBrush().
230 II.

13 .
, !
, ,
, .
QAppilcation::setPalette () . ,
3 7 .
13.2 , .
:

, .
, .

13.2. main.cpp

int main (int argc, char** argv)


{
QApplication app(argc, argv);
QPalette pal(Qt::red, Qt::blue);
QApplication: isetPalette(pal);

,
. ,
. 3- , ,
. ,
. , ,
QApplication::setPalette().
III

...
.

14.
15.
16.
14

-

, .
, ?
,

,
.
- . ,
,
. . ,
, .
, , , .
.
- , .
?
, ,
, . ,
. ,
.
(,
- ). ,
, , ,
.
,
, ,
. , QMouseEvent
.
,
. ,
mouse PressEvent ( )
clicked ( ) .

, Qt virtual
protected.
protected.
234 III.


,
. , ,
, .
Qt : , ,
. . 14.1 Qt.
. 14.1, QEvent .
. -

QEvent
J QMimeSource

( QAccessibleEvent QDropEvent

iQActionEvent I QDragMoveEvent
[QChildEvent 1 QDragEnterEvent
] QClipboardEvent QGraphicsSceneEvent

| QCIoseEvent | QGraphicsSceneContextMenuEvent

| QCustomEvent [ QGraphicsSceneDragDropEvent

[ QDragLeaveEvent _ [ QGraphicsSceneHelpEvant

j QDragRasponsaEvant _ | QGraphicsScenoHoverEvent

| QDynamicPropertyChangeEvent | QGraphicsSceneMouseEvent

|QFUaOpanEvant | QGraphicsSceneMoveEvent

[Qit acmEmanl | QGraphicsSceneResizeEvent

[QGasturaEvent _ | QGraphicsSceneWheelEvent

| QHelpEvent QlnputEvent

[QHideEvent QContextMenuEvent

iQHovarEvent _ [ QKeyEvent

|[ QlconDragEvant _ QMouseEvent

| QlnputMethodEvent | QTableEvent

| QMoveEvent ( QTouchEvent

~jQPaintEvent QWheelEvent

[ QResizeEvent QToolBarChangeEvent

| QShortcutEvent QUpdateLaterEvent

|| QShowEvent _ ~[QWhat*ThiClickdEvant
[QStatusTipEvent | QWindowStateChangeEvent

|QTlmarEvent
. 14.1.
14. 235

,
QEvent QEvent::type().
QEvent accept ( ) ignore ( ) ,
,
. ignore (),
-.
QinputEvent ,
(. . 14.1). : modifiers ( ) .
-
<Ctrl>, <Shift> <Alt>, .
. 14.1.

14.1. Qt

(HEX)

NoModifier 0

ShiftModifier 2000000 <Shift>

ControlModifier 4000000 <Ctrl>


AltModifier 8000000 <Alt>


QCoreApplication::(). , ,
QObject. ,

QCoreApplication::(). Qt
. , ,
QPaintEvent
() ,
.
(paintEvent ( ) ) .



. ,
.
, .
, keyPressEvent ( )
keyReleaseEvent ( ) QKeyEvent.


QKeyEvent
QKeyEvent .
, , ASCII-
236 III.

(American Standard Code for Information Interchange,


). QWidget:: keyPressEvent ()
QWidget::keyReleaseEvent ( ), QWidget.
, <Shift>, <Ctrl>, <Alt>, <Esc> <F1>-
<F12>. <Tab>
<Shift>, QWidget :: event ( )
.
keyPressEvent ( )
, keyReleaseEvent ( ) .
QKeyEvent ::key ( ) ,
. ,
, Qt (. 14.2).
, . 14.2:
20 3F ASCII- (. 7);
30 39 ,
;
41 5 . ,
ASCII- (. 7);
1000030 1000052 . 35,
. 14.2 12, ;
100009, 1000025 1000026
;

1000010 1000017 ;

1000020 1000023 ;

, 1000001, 1000004 1000005 ,
.
,
, : <Shift>, <Ctrl> <Alt>,
modifiers ().
text() Unicode-,
. ,
. .
key ( ) ,
(. . 14.1).
, QWidget,
:
void MyWidget::keyPressEvent (QKeyEvent* )
{
switch (pe->key()) {
case Qt::Key_Z:
if (pe->modifiers () & Qt::ShiftModifier) {
// -
}
14. 237

14.2. Key Qt



(HEX) (HEX) (HEX)

Key_Space 20 Key_B 42 Key Insert 1000006

Key NumberSign 23 Key_C 43 Key_Delete 1000007

Key Dollar 24 Key_D 44 Key_Pause 1000008

Key Percent 25 Key_E 45 Key Print 1000009

Key Ampersand 26 Key_F 46 Key Home 1000010

Key Apostrophe 27 Key_G 47 Key End 1000011

Key ParenLeft 28 Key_H 48 Key Left 1000012

Key ParenRight 29 Key_I 49 Key Up 1000013

Key Asterisk 2A Key_J 4A Key Right 1000014

Key Plus 2B Key_K 4B Key Down 1000015

Key Comma 2C Key_L 4C Key_PageUp 1000016

Key Minus 2D Key M 4D Key PageDown 1000017

Key Period 2E Key_N 4E Key Shift 1000020

Key Slash 2F Key_0 4F Key Control 1000021

Key 0 30 Key_P 50 Key Meta 1000022

Key 1 31 Key_Q 51 Key Alt 1000023

Key 2 32 Key_R 52 Key CapsLock 1000024

Key 3 33 Key_S 53 Key NumLock 1000025

Key 4 34 Key_T 54 Key ScrollLock 1000026

Key 5 35 Key_U 55 Key_Fl 1000030

Key 6 36 Key_V 56 Key_F2 1000031

Key_7 37 Key_W 57 Key_F3 1000032

Key_8 38 Key_X 58 Key_F4 1000033


Key_9 39 Key_Y 59 Key_F5 1000034

Key Colon Key_Z 5A Key_F6 1000035

Key_Semicolon 3B Key Backslash 5C Key_F7 1000036


Key_Less 3C Key_Escape 1000000 Key_F8 1000037
Key_Equal 3D Key_Tab 1000001 Key_F9 1000038
Key_Greater 3E Key_Backspace 1000003 Key_F10 1000039
Key_Question 3F Key Return 1000004 Key_Fll 100003A

Key_A 41 Key Enter 1000005 Key_F12 100003B


238 III.

else {
// -
}
break;
default ;
QWidget: ;keyPressEvent(); //

, <Z> <Shift>.
, modifiers ( ) , ,
. 14.1.

QFocusEvent
- ,
.
, , . QFocusEvent
.
focusinEvent focusOutEvent ( )
. QFocusEvent
, , ,
. ,
(focusInEvent()) (focusOutEvent( ) ) .

.
QPaintEvent
Qt (double buffering).
QWidget: : setAttribute(Qt : :WA_PaintOnScreen). ,
: ,

. ,
QPaintEvent. QPaintEvent
. ,
show ( ) ,
repaint ( ) update ( ) . paintEvent ( ) ,
.
. ,
,
.
region!) contains!) ,
. :
MyClass::paintEvent(QPaintEvent* )
{
QPainter painter(this);
QRect r(40, 40, 100, 100);
if (pe->region().contains(r)) {
painter.drawRect(r);
1
1
IV .
14. 239


,
, ,
.
,
,
, .
,
. , ,
, . ,
, , ,

.

QMouseEvent
, ,
,
.
mousePressEvent(), mouseMoveEvent(), mouseReleaseEvent() mouseDoubleClickEvent().
mousePressEvent ( ) ,
. , ,
, ,
. mouseMoveEvent { ) ,
mouseReleaseEvent ( ) .
mouseMoveEvent ( ) ,
.
.
, setMouseTracking ( ) QWidget,
true.
mouseDoubleClickEvent ()
.

globalxo, globalYO, () (),
. pos ( ) globalPos ( ) . pos ( )
QMouseEvent
. (
), globalPos ( ) .
button ( ) , ,
(. 14.3). buttons ()
. 14.3 . , ,
| () .
,
- <Ctrl>, <Shift> / <Alt>,
modifiers(), QinputEvent (. . 14.1 . 14.1).
240 III.

14.3. MouseButton Qt

NoButton 0

LeftButton 1
Right But ton 2

MidButton 4

mouseDoubleClickEvent () mouse PressEvent () ,


.
400 ,
setDoubleClicklnterval () QApplication.
.
14.1-14.3. . 14.2
<Ctrl>.

. 14.2. ,

main () ( 14.1)
MouseObserver resize () .
show ( ) .

14.1. main.cpp

#include <QtWidgets>
#include "MouseObserver. h"

int main(int argc, char** argv)


{
QApplication app(argc, argv);
MouseObserver wgt;

.
wgt resize (250, 130);
wgt . show ( ) ;

return app . exec ( ) ;


14. 241

MouseObserver ( 14.2) :
mousePressEvent ( ) ;
mouseReleaseEvent ( ) ;
mouseMoveEvent ( ) .
dumpEvent ( ) .
( ) -
modifiersInfo ( ) buttonsInfo().

14.2. MouseObserver.h

#pragma once

# include <QtWidgets>

// ====================================================================
class MouseObserver : public QLabel {
public:
MouseObserver(QWidget* pwgt = 0);

protected:
virtual void mousePressEvent (QMouseEvent* pe);
virtual void mouseReleaseEvent(QMouseEvent* pe);
virtual void mouseMoveEvent (QMouseEvent* pe);

void dumpEvent (QMouseEvent* pe, const QString& strMessage);


QString modifiersInfo (QMouseEvent* pe );
QString buttonslnfo (QMouseEvent* pe );
};

( 14.3) setAlignment ()
AlignCenter .
mousePressEvent(), mouseReleaseEvent ( ) mouseMoveEvent ( ) ,
,
dumpEvent ( ) ,
, .
modifiersinfo ( ) -,
modifiers ().
buttonslnfo().
dumpEvent() setText().

14.3. MouseObserver.cpp

#include "MouseObserver.h"

//
MouseObserver::MouseObserver(QWidget* pwgt /*= 0*/) : QLabel(pwgt)
{
setAlignment(Qt::AlignCenter);
242 III.

setText("Mouse interactions\n(Press a mouse button)");

//
/*virtual*/void MouseObserver::mousePressEvent(QMouseEvent* pe)
{
dumpEvent(pe, "Mouse Pressed");
}

//
/*virtual*/void MouseObserver: rmouseReleaseEvent(QMouseEvent* pe)
{
dumpEvent(pe, "Mouse Released");

//
/virtual*/ void MouseObserver::mouseMoveEvent(QMouseEvent* pe)
{
dumpEvent(pe, "Mouse Is Moving");

//
void MouseObserver::dumpEvent(QMouseEvent* pe, const QStrings strMsg)
{
setText(strMsg
+ "\n buttons()=" + buttonslnfo(pe)
+ "\n x()=" + QString::number(pe->x())
+ "\n y()=" + QString::number(pe->y())
+ "\n globalX()=" + QString::number(pe->globalX())
+ "\n globalY()=" + QString::number(pe->globalY())
+ "\n modifiers()=" + modifierslnfo(pe)

//
QString MouseObserver::modifierslnfo(QMouseEvent* pe)
{
QString strModifiers;

if(pe->modifiers() & Qt::ShiftModifier) {


strModifiers += "Shift ";
}
if(pe->modifiers() & Qt::ControlModifier) {
strModifiers += "Control ";
}
if(pe->modifiers() & Qt::AltModifier) {
strModifiers += "Alt";
}
return strModifiers;
14. 243

QString MouseObserver::buttonsInfo(QMouseEvent* )
{
QString strButtons;

if(pe->buttons() & Qt::LeftButton) {


strButtons += "Left ";
}
if(pe->buttons() & Qt::RightButton) {
strButtons += "Right
}
if(pe->buttons() & Qt::MidButton) {
strButtons += "Middle";
}
return strButtons;
}

QWheelEvent
, , ,
QWheelEvent,
QinputEvent (. . 14.1).
QWheelEvent , .
wheelEvent ( )
, , ,
. buttons(), pos()
giobaiPosO, QMouseEvent,
QWheelEvent delta(),
. , ,
.

enterEventQ leaveEventQ
,
. , , ,
. enterEvent ( ) QEvent
, . leaveEvent ( )
QEvent ,
.

. QTimerEvent
QTimerEvent , .
timerEvent().
. , ,
Qwidget, :
void MyClass::timerEvent(QTimerEvent* e)
{
if (event->timerld() == myTimerld) {
244 III.

// -
}
else {
QWidget::timerEvent(); //

37.

(drag & drop)


29.
.

QDragEnterEvent
QDragEnterEvent QDragMoveEvent (. . 14.1).
. ,
, , dragEnterEvent {) .

QDragLeaveEvent
QDragLeaveEvent ,
, , .
dragLeaveEvent ( ) .

QDragMoveEvent
,
.
dragMoveEvent ( ) .

QDropEvent
QDropEvent dropEvent ( )
.


QChildEvent
-.
childEvent ( ) , QObject.
QChildEvent: : child () .
QChildEvent: : added () QChildEvent: : removed!) -
-.

QCIoseEvent
QCIoseEvent .
QWidget :: close ( ) . QCIoseEvent
14. 245

closeEvent ( ) , ,
. ,
.

accept ( ) ignore ( ) ,
. accept ( ) ,
hide ( ) . ignore ( )
.

QHideEvent
.
hide ( ) , .
QHideEvent hideEvent ( ) .

QMoveEvent
QMoveEvent .
. QMoveEvent
moveEvent ( )
, pos ( ) oldPos ( ) .

QShowEvent
show ( ) .
QShowEvent showEvent ( ) .

QResizeEvent
.
QResizeEvent. resizeEvent ( )
, size()
oldSize ( ) .
:
;
-.
( 14.4) resizeEvent ( ) .
,
(. 14.3).

. 14.3. resizeEvent ()
246 III.

14.4 main (
ResizeObserver), resized.
resizeEvent ( ) ,
. size QSize,
( width ( ) height ( ) ).
QString::number () .
,
QLabel::setText().

14.4. main.cpp

#include <QtWidgets>

// ======================================
class ResizeObserver : public QLabel {
public:
ResizeObserver(QWidget* pwgt = 0) : QLabel(pwgt)
{
setAlignment(Qt::AlignCenter);
}

protected:
virtual void resizeEvent(QResizeEvent* pe)
{
setText(QString("Resized")
+ "\n width()=" + QString::number(pe->size().width())
+ "\n height()=" + QString::number(pe->size().height())
);

//
int main(int argc, char** argv)
{
QApplication app(argc, argv);
ResizeObserver wgt;

wgt.resize(250, 130);
wgt.show();

return app.exec( );
}


, Qt,
, , Qt,
QEvent. QEvent
, -
14. 247

, QEvent::User ( 1000 . . 14.4),


.
. :
class MyEvent : public QEvent {
public:
MyEventO : QEvent((Type)(QEvent::User + 200))
(
1

QString info()

return "CustomEvent";

QCoreApplication::
sendEventO QCoreApplication::postEvent ( ) (. 16),
QObject::event() QObject::CustomEvent().

event()
,
, ( ) QCoreApplication
QApplication. QApplication ,
. event ( ) ,
,
, , mousePressEvent ( )
(. 14.4).

. 14.4.
248 III.

event ( ) , ,
. , ,
,
.
event ( ) , ,
. ,
,
. event ( ) ,
.
event () QEvent.
QEvent, ,
,
QEvent . event ( ) ,
. type ( ) .
(. 14.4),
.

14.4.


None 0 ThreadChange 22
Timer 1 WindowActivate 24
MouseButtonPress 2 WindowDeactivate 25
MouseButtonRelease 3 ShowToParent 26
MouseButtonDblClick 4 HideToParent 27
MouseMove 5 Wheel 31
KeyPress 6 WindowTitleChange 33
KeyRelease 7 WindowlconChange 34
Focusln 8 ApplicationWindowIconChange 35
FocusOut 9 ApplicationFontChange 36
Enter 10 ApplicationLayoutDirectionChange 37
Leave 11 ApplicationPaletteChange 38
Paint 12 PaletteChange 39
Move 13 Clipboard 40
Resize 14 Speech 42
Create 15 SockAct 50
Destroy 16 ShortcutOverride 51
Show 17 DeferredDelete 52
Hide 18 DragEnter 60
Close 19 DragMove 61
Quit 20 DragLeave 62
ParentChange 21 Drop 63
14. 249

14.4 ()

DragResponse 64 WindowUnblocked 104


ChildAdded 68 WindowStateChange 105
ChildPolished 69 MouseTrackingChange 109
ChildRemoved 71 ToolTip 110
ShowWindowRequest 73 WhatsThis 111
PolishRequest 74 StatusTip 112
Polish 75 ActionChanged 113
LayoutRequest 76 ActionAdded 114
UpdateRequest 77 ActionRemoved 115
UpdateLater 78 FileOpen 116
ContextMenu 82 Shortcut 117
InputMethod 83 WhatsThisClicked 118
AccessibilityPrepare 86 AccessibilityHelp 119
TabletMove 87 ToolBarChange 120
LocaleChange 88 ApplicationActivated 121
LanguageChange 89 ApplicationDeactivated 122
LayoutDirectionChange 90 QueryWhatsThis 123
Style 91 EnterWhatsThisMode 124
TabletPress 92 LeaveWhatsThisMode 125
TabletRelease 93 ZOrderChange 126
IconDrag 96 HoverEnter 127
FontChange 97 HoverLeave 128
EnabledChange 98 HoverMove 129
ActivationChange 99 AccessibilityDescription 130
StyleChange 100 ParentAboutToChange 131
IconTextChange 101 WinEventAct 132
ModifiedChange 102 MenubarUpdated 153
WindowBlocked 103 User 1000

event() , , , QWidget,
:

bool MyClass::event(QEvent* )
{
if (pe->type() == QEvent::KeyPress) {
QKeyEvent* pKeyEvent = static_cast<QKeyEvent*>(pe);
250 III.

if (pKeyEvent->key() == Qt::Key_Tab) {
// -
return true;

if (pe->type() == QEvent::Hide) {
// -
return true;
}
return QWidget::event(pe);
}

true ,
. . false
-.
, .



,
, (
). :
for (int i = 0; i < 1000; ++i) {
//
}

, ,
, , ,
, ,
.

(. 38). QCoreApplication::
processEvents ( ) , ,
. :
for (int i = 0; i < 1000; ++i) {
//
qApp->processEvents(); //
}


,
.
14. 251

-
, , . .
. ,
.
,
. ,
event ( ) , . event ( )
. ,

, ,
keyPressEvent ( ) . event ( )
QEvent, . QEvent ::type ( )
.

event(), .
.
,
. QPaintEvent ,
.
paintEvent( ).
mousePressEvent , mouseMoveEvent(),
mouseReleaseEvent ( ) mouseDoubleClickEvent ( ) .
giobalxo, globalYO, (), , pos()
globalPos().
keyPressEvent ( )
keyReleaseEvent () . keyPressEvent ( ) ,
. keyReleaseEvent ()
.
(),

.
15

, , .

, , ,
. Qt
,
, ,
/ .
QObject: : installEventFilter ( ) ,
, .
, ,
. ,
( ), .
,
.
, .
, , ,
- ,
.
, QObject .
, ,
.
,
, ,
, .


, QObject
eventFilter ( ) . ,
, .
: , ,
.
eventFilter true, ,
, false ,
, .
15. 253

( 15.1-15.3) ,
(. 15.1).
, .

EventFilter
1=1
' I
[QLineEdit |

~~1 EventFilter
QLabel
1 .=, I 0 53 1 1
EventFilter 1 1=]
Ij 11
[ QPushButton

. 15.1. ,

main (), 15.1, : QLineEdit, QLabel


QPushButton. installEventFilter
, .
, .

.

15.1. main.cpp

tinclude <QtWidgets>
#include "MouseFilter.h"

int main (int argc, char** argv)


{
QApplication app(argc, argv);

QLineEdit txt("QLineEdit");
txt.installEventFilter(new MouseFilter(&txt));
txt.show();

QLabel lbl("QLabel");
1.installEventFilter(new MouseFilter(&lbl));
1.show();

QPushButton cmd("QPushButton");
cmd.installEventFilter(new MouseFilter(&cmd));
cmd.show();

return app.exec( );
1

15.2 eventFilter(),
, ,
. ,
, .
254 III.

15.2. MouseFilter.h

#pragma once

#include <QObject>

/ / =============================================
class MouseFilter : public QObject {
protected:
virtual bool eventFilter(QObject*, QEvent*);

public:
MouseFilter(QObject* pobj = 0);

15.3 eventFilter () QEvent::MouseButtonPress,


. ,
QMouseEvent.
button ( ) QMouseEvent, ,
. ,
, true .
false .

15.3. MouseFilter.cpp

#include <QtWidgets>
#include "MouseFilter.h"

//
MouseFilter::MouseFilter(QObject* pobj/*= 0*/)
: QObject(pobj)
{
}

//
/*virtual*/bool MouseFilter::eventFilter(QObject* pobj, QEvent* pe)
{
if (pe->type() == QEvent::MouseButtonPress) {
if (static_cast<QMouseEvent*>(pe)->button() == Qt::LeftButton) {
QString strClassName = pobj->metaObject()->className();
QMessageBox::information(0, "Class Name", strClassName);
return true;
}
}
return false;
}

,
.
15. 255

, ,
.
installFilter ( ) QCoreApplication QApplication { ) .
, ,
.
,
, .
QCoreApplication::
notify () .

. Qt
,
.
. , QObject
eventFilter().
16


.
.

, . ,
, .

QCoreApplication: sendEventO postEvent().
, , .
, sendEvent ( ) ,
,
postEvent ( ) .
( 16.1 16.2),
<> <Z> (. 16.1).

. 16.1. ,

, 16.1, txt QLineEdit,


.
QKeyEvent. , ,
( QEvent: : Keypress).
, Keypress
KeyRelease ( ),
, ,
, , QLineEdit .
. -,
, Qt: :NoModifier ,
- (. . 14.1). ,
ASCII- (
65, , ).
, sendEvent ( )
, , ,
, , new, -
16. 257

keypress keyRelease,
.

16.1. main.cpp

#include <QtWidgets>

int main (int argc, char** argv)


{
QApplication app (argc, argv);

QLineEdit txt("User input: );


txt.show();
txt.resize(300, 20);

int i;
for (i = 0; i < Qt::Key_Z Qt::Key_A + 1; ++i) {
QChar ch = 65 + i;
int nKey = Qt::Key_A + i;
QKeyEvent keyPress(QEvent::KeyPress, nKey, Qt::NoModifier, ch);
QApplication::sendEvent(&txt, SkeyPress);

QKeyEvent keyRelease(QEvent::KeyRelease, nKey, Qt::NoModifier, ch);


QApplication::sendEvent(&txt, skeyRelease); }

return app.exec();
}

- ,
, 16.2.

16.2.

void mousePress(QWidget* pwgt,


int x,
int y,
Qt::MouseButton bt = Qt::LeftButton,
Qt::MouseButtons bts = Qt::LeftButton
)
{
if (pwgt) {
QMouseEvent* pePress =
new QMouseEvent(QEvent::MouseButtonPress,
QPoint(x, y),
bt,
bts,
Qt::NoModifier
);
QApplication::postEvent(pwgt, pePress);
258 III.

mousePressO ,
, ,
.
,
.
, QMouseEvent,
( pwgt)
postEvent().
.
.
15.

.
, ,
.
( 16.3 16.4) <Z>
<>. <Z>
(. 16.2). , ,
.

EvenlChamje
.

. 16.2. ,

16.3 QLineEdit show


pFilter, -
txt.
installEventFilter().

16.3. main.cpp

#include <QtWidgets>
#include "KeyFilter.h"

int main(int argc, char** argv)


{
QApplication app(argc, argv);

QLineEdit txt;
txt.show();

KeyFilter* pFilter = new KeyFilter(&txt);


txt.installEventFilter(pFilter);

return app.exec();
16. 259

16.4 eventFilter () QEvent::


Keypress, .
QKeyEvent,
key ( ) ,
. <>.
true, , .
, eventFilter ( ) ,
, false, , ,
.

16.4. KeyFilter.h

#pragma once

#include <QtWidgets>

/ / ==========================================================
class KeyFilter : public QObject {
protected:
bool eventFilter (QObject* pob j , QEvent* pe)
{
if (pe->type() == QEvent :: KeyPress) {
if (( (QKeyEvent* )pe)->key() == Qt::Key_Z) {
QKeyEvent keyEvent (QEvent ::KeyPress,
Qt : : Key_A,
Qt: :NoModifier,
"A"
);
QApplication : : sendEvent (pobj , & keyEvent ) ;
return true;
}
}
return false;
}

public:
KeyFilter (QObject* pobj = 0)
: QObject (pobj )
{
}
};

.
QApplication: : sendEvent ( ) QApplication: :
postEvent ( ) .
.
IV

, .

17.
18.
19.
20.
21.
22.
23. OpenGL
24.
25.
26.
27.
17


...
...
. . ,

.
, 70 % ,
.

, , , ,
.


.
, .

: QPoint QPointF.
X Y, X
, a Y .
, Qt , Y
(. 17.1).
QPoint , a QPointF
. , ,
, ,
. / /
Y. : ptl pt2 (. . 17.1):
QPoint ptl (10, 20);
QPoint pt2(20, 10);
QPoint pt3; // (0, 0)
pt3 = ptl + pt2;

. :
QPoint pt (10, 20) ;
pt *= 2; // pt = (20, 40)
264 IV.

. 17.1.

(X, Y) () ( ) .
setx ( ) setY().
, . :
QPoint pt(10, 20);
pt.rx() += 10; // pt = (20, 20)

== () ! = (
). :
QPoint pt1(10, 20);
QPoint pt2(10, 20);
bool b = (ptl == pt2); // b = true
, X Y ,
isNuii(). :
QPoint pt; // (0, 0)
bool b = pt.isNullO; // b = true

manhattanLength ( ) X Y.
:
QPoint pt(10, 20);
int n = pt.manhattanLength(); // n = 10 + 20 = 30

,
. 42 + Y2 .


QSize QSizeF .
. QPoint,
, /
/.
QSize QSizeF, QPoint, QPointF,
==, ! = isNuii ( ) , true ,
.
1 7. 265

width () height ().


setwidthO setHeight().
rwidth ( ) rheight ( ) . :
QSize size(10, 20);
int n = size.rwidth()++; // n = 11; size = (11, 20)

scale ( ) ,
.
(. 17.2), :
Qt:: ignoreAspectRatio ;
Qt : : KeepAspectRatio ,
;
Qt : :KeepAspectRatioByExpanding
scale(), .
. 17.2, sizel, size2 size3
:
QSize sizel(320, 240);
sizel.scale(400, 600, Qt::IgnoreAspectRatio); // => (400, 600)

QSize size2(320, 240);


size2.scale(400, 600, Qt: -.KeepAspectRatio); // => (400, 300)

QSize size3(320, 240);


size3.scale(400, 600, Qt: -.KeepAspectRatioByExpanding); // => (800, 600)

. 17.2.
266 IV.

QRect QRectF
( ) .
, , ( ) . ,
. 17.3, :
QPoint pt(10, 10);
QSize size(20, 10);
QRect r(pt, size);
X Y
( ) ( ) .
setx( ) setY().
size (), QSize.
, : width ( )
height () . setSizeO,
setwidth( ) setHeight().

. 17.3. . 17.4.


QLine QLineF , ,
.
xl ( ) yl ( ) , 2 ( ) 2().
pi ( ) 2 ( ) ,
QPoint/QPointF, . dx() dy()
X Y . ,
. 17.4, :
QLine line(10, 10, 30, 20);

QLine QLineF
==, !=
isNull (), true ,
.
1 7. 267

( ) , ,
. Qt QPolygon QPolygonF,
.
QVector<QPoint> QVector<QPointF>.

. (. 17.5),
:
QPolygon polygon;
polygon QPoint(10, 20) QPoint(20, 10) QPoint(30, 30);

. 17.5.

, , , ,
,
. ,
. ,
, ,
.
.
10 .

, . Qt : RGB
(Red, Green, Blue , , ), CMYK (Cyan, Magenta, Yellow Key
color , , ) HSV (Hue, Saturation,
Value , , ).

QColor
QColor RGB HSV.
QColor. QColor
== ! =, .
268 IV.

RGB
, , .
RGB (Red, Green, Blue , , ).
, 255 (. 17.6)
( ).

. 17.6, .
, , . ,
, .
0 255 ( 0 1
), 0 , 255

.
,
. , ,
, .
RGB QColor
. QColor
, .
, ,
, . :
QColor colorBlue(0, 0, 255, 128);

QColor red ( ),
green ( ), blue ( ) alpha ( ) .
, : redF(), greenF(), blueF( ) alphaF(). -
1 7. 269

getRgb ( ) ,
, :
QColor color(100, 200, 0);
int , g, b;
color.getRgb(&r, &g, &b);
RGB , , ,
, set ( get, ),
. QRgb,
32- .
qRgb ( ) qRgba ( ) ,
, . QRgb
32- . ,
:
QRgb rgbBluel = qRgba(0, 0, 255, 255); //
QRgb rgbBlue2 = qRgb(0, 0, 255);
QRgb rgbBlue3 = OxOOOOOOFF;

qRed(), qGreen(), qBlue( ) qAlpha ( )


.
QRgb QColor setRgb ( ) :
QRgb rgbBlue = OxOOOOOOFF;
QColor colorBluel(rgbBlue);
QColor colorBlue2;
colorBlue2.setRgb(rgbBlue);
QRgb QColor
rgb().
, , :
QColor colorBluel("#0000FF");
QColor colorBlue2;
colorBlue2.setNameColor("#0000FF");

HSV
HSV (Hue, Saturation, Value , , )
, RGB,
. ,
, , .
,
(. 17.7). :
(Hue) ,
, , . ., ,
0 360 ;
(Saturation) .
0 255. , 255
, -
270 IV.

, .
, ,
128, 0,5 , ;
(Value) .
, .
0 255 ( 0 1
).

HSV
QColor::setHsv () QColor::setHsvF ():
color.setHsv(233, 100, 50);

HSV,
getHsv ( ) ( , getHsvF ( )).
RGB- HSV-
:
QColor color(100, 200, 0);
int h, s, v;
color.getHsv(&h, &s, &v);

CMYK
CMYK (Cyan, Magenta, Yellow, Key color
, ,
, ) .
, RGB,
1 7. 271

255 (. 17.8)
. RGB, ,
. ,
,
.

,
: , .
,
.
(Key color) .


, Key color, a Black. Black
,
(Blue), RGB.

CMYK ,
RGB HSV. QColor getCmyk ( ) getCmykF ( )
, setcmyk ( ) setCmykF ( ) .

( 256)
. .
. . 17.9 ,
RGB(200, 75, 13), 3.
272 IV.

. 17.9. ,


. 17.1 , Qt.
, 17 . ,
, ,
, .

19. , :
Qt::colorO Qt::colorl .

17.1. GlobalColor Qt

RGB-
black
white (255, 255, 255)
darkGray (128, 128, 128) -
gray (160, 160, 164)
lightGray (192, 192, 192) -
red (255, 0, 0)

green (0, 255, 0)


blue (0, 0, 255)
cyan (0, 255, 255)
magenta (255, 0, 255)
yellow (255, 255, 0)
darkRed (128, 0, 0) -
1 7. 273

17.1 ()

RGB-
darkGreen (0, 128, 0) -
darkBlue (0, 0, 128) -
darkCyan (0, 128, 128) -
darkMagenta (128, 0, 128) -
darkYellow (128, 128, 0) -

QColor lighter () darker (),


, . lighter ()
darker () , .
RGB HSV (Value)
( darker () ) ( ),
, RGB.
:
QColor color = QColor (Qt :: red) .darker (160) ;

,
.
Qt , .
QPoint/QPointF X ,
. QSize/QSizeF
. QRect/QRectF ,
QPoint/QPointF QSize/QSizeF. QLine/QLineF QPolygon/QPolygonF
.
Qt : RGB, CMYK HSV. RGB
,
: , . CMYK
. HSV : (Hue),
(Saturation) (Value), , , .
TrueColor .
, 8 .
,
.
QColor
, RGB,
CMYK HSV ( ), , .
18



.
,
?
,


, .
, ,
.

(Arthur) ,
QPainter OpenGL.
:
,
.
QPainter, QPaintEngine
QPaintDevice (. 18.1).
QPaintEngine QPainter QPaintDevice
,
. ,
.
, ,
QPainter. , , , (
), , , . ,
,
QPainter (antialiasing),
.
QPaintDevice
. QPaintDevice ,
. , . 18.2.
, QPaintEvent
(. 14). ,
, , ,
QWidget::paintEvent()
, . QPaintEvent
region ( ) , . QPaintEvent::
rect ( ) , .
18. 275

QPaintDevice

[QWidget

|j3CustomRasterPaintDevjcej
ljGtramebufferObject
'[QGLPixeIBuffer |
(Qlmagc |

fQSvgGenerator~|
QPixmap

| QBitmap
. 18.1.
. 18.2.

Qt (double
buffering).
.
(). ()
. ,
paintEvent().
, ,
- (. 17). 0 255.
0 , , 255
.

QPainter
QPainter, QPainter,
. , ,
. ,
QPaintDevice (. 18.3). , ,
, .

QPainter, ,
. ,
QPainter::begin(). begin ( ) ,
QPainter.
begin
QPainter::end ( ) ,
, ( 18.1).
276 IV.


QCustomRasterPaintDevice QPrinter QPicture QWidget QPixmap
QBitmap
Qlmage
QGLFramebufferObject
QGLPixelBuffer

QPainter
. 18.3. QPainter

18.1. QPainter

QPainter painterl;
QPainter painter2;

painterl.begin(this);
//
painterl.end();

painter2.begin(this);
//
painter2.end();

QPainter (
18.2).

18.2. QPainter

QPainter painter;

painter.begin(this); //
//
painter.end();

QPixmap pix(rect());
painter.begin(&pix); //
//
painter.end();

QPainter , .
, , ,
. . , , -
18. 277

QPainter : : save ( ) ,
QPainter : : restore ( ) .




Qt. .

. : ,
. QPainter: :setPen(),
QPen. ,
. 18.1.

18.1. PenStyle Qt

( = 4)
NoPen 0
SolidLine 1
DashLine 2
DotLine 3

DashDotLine 4

DashDotDotLine 5

,
. , , ,
QPen : : setwidth ( )
, .
, ,
NoPen. , ? ,
, ,
.
QPen: :setColor ,
QColor. ,
. QPainter
setPen ( ) :
QPainter painter (this) ;
painter . setPen (QPen (Qt :: red, 3, Qt :: DashLine) ) ;

setcapstyle ( ) ,
Qt : : Fiatcap (
), Qt : : SquareCap (
) Qt : : RoundCap ( ).

set Joinstyle ( ) , : Qt: : Miter join (
278 IV.

), Qt::BevelJoin ( )
Qt::RoundJoin ( ). .

,
. QBrush QBrush.
: .
QPainter::setBrush(),
QBrush , . 18.2.
, QPainter::setBrush ( ) NoBrush.

18.2. BrushStyle Qt ()

:
QPainter painter(this);
painter.setBrush(QBrush(Qt::red, Qt::HorPattern));
. 18.2 ,
TexturePattern. ,
setTexture ( ) .
(. 18.4):
QPixmap pix(":/fruits.jpg");
painter.setBrush(QBrush(Qt::black, pix));
painter.drawEllipse(0, 0, 300, 150);
18. 279

. 18.4.


.
,
.
. Qt
: (linear), (conical) (radial).
(linear) QLinearGradient.
(color stops) ,
. 18.3 .

18.3.

QPainter painter(this);
QLinearGradient gradient(0, 0, width(), height());
gradient.setColorAt(0, Qt::red);
gradient.setColorAt(0.5, Qt::green);
gradient.setColorAt(1, Qt::blue);
painter.setBrush(gradient);
painter.drawRect(rect());

18.3
. 0 1, 0
, 1 .
(. 18.5).
(conical) QConicalGradient
.
. 18.4
(. 18.6).

18.4.

QPainter painter(this);
QConicalGradient gradient(width() / 2, height() /2, 0);
gradient.setColorAt(0, Qt::red);
gradient.setColorAt(0.4, Qt::green);
gradient.setColorAt(0.8, Qt::blue);
280 IV.

gradient.setColorAt(1, Qt::red);
painter.setBrush(gradient);
painter.drawRect( rect());

. 18.5. . 18.6. . 18.7.


(radial) QRadialGradient
, . .
,
.
18.5, . 18.7.

18.5.

QPainter painter(this);
QPointF ptCenter(rect().center());
QRadialGradient gradient(ptCenter, width() / 2, ptCenter);
gradient.setColorAt(0, Qt::red);
gradient.setColorAt(0.5, Qt::green);
gradient.setColorAt(1, Qt::blue);
painter.setBrush(gradient);
painter.drawRect( rect());

(Anti-aliasing)
, ,
, (. 18.8). ,
, , .
(Anti-aliasing).
, ,
, .
, .
.
QPainter setRenderHint():
painter.setRenderHint(QPainter::Antialiasing, true);
18. 281

. 18.8. () ()

,
,
. , drawRect ( )
.
, .
, . ,
, (0,5; 0,5).
(0; 0), QPainter 0,5,
(0,5; 0,5).
. ,
(50; 50),
(49,5; 49,5), (49,5; 50,5), (50,5; 49,5) (50,5; 50,5).
(49,5; 49,5),
.


. 18.6
(. 18.9).

18.6. drawPoint()

QPainter painter(this);
painter.set Pen(QPen(Qt::black, 3) );

int n = 8;
for (int i = 0; i < n; ++i) {
qreal fAngle =2 * 3.14 * i / n;
282 IV.

qreal = 50 + cos(fAngle) * 40;


qreal = 50 + sin(fAngle) * 40;
painter.drawPoint(QPointF(x, ));

. 18.9. . 18.10. . 18.11.



(. 18.10)
drawLine () , (xl, yl) (2, 2)
QPointF ( 18.7).

18.7. drawLine ()

QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true);
painter.drawLine(QPointF(10, 10), QPointF(90, 90));

drawPolyLine ( ) , ,
. , (
). . 18.8
, . 18.11.

18.8. drawPolylineO

QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true);

int n = 8;
QPointF a[n];
for (int i = 0; i < n; ++i) {
qreal fAngle =2 * 3.14 * i / n;
qreal x = 50 + cos(fAngle) * 40;
qreal = 50 + sin(fAngle) * 40;
a[i] = QPointF(x, y);
}
painter.drawPolyline(a, n);
18. 283


,
. Qt
: fillRecto eraseRecto.
. fillRecto .
(, ) (, ) .
.
eraseRect ( ) ,
. , .
, filiRect ()
, paietteBackgroundCoior . 18.9
filiRect ( ) eraseRect ( ) , . 18.12.

18.9. fillRecto eraseRecto

QPainter painter(this);
QBrush brush(Qt::red, Qt::Dense4Pattern);
painter.filiRect(10, 10, 100, 100, brush);
painter.eraseRect(20, 20, 80, 80);

. 18.12. . 18.13.


, QPen QBrush.
, ,
QPainter;:setBrush() QBrush::NoBrush.
QPainter::setPen ( )
QPen::NoPen.
drawRecto (. 18.13).
: (, ) , .
QRect ( 18.10).

18.10. drawRecto

QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true);
284 IV.

painter.setBrush(QBrush(Qt::red, Qt::DiagCrossPattern));
painter.setPen(QPen(Qt::blue, 3, Qt::DashLine));
painter.drawRect(QRect(10, 10, 110, 70));

drawRoundRect ( ) (. 18.14).
.
,
X Y . ,
100 .
QRect ( 18.1 1).

18.11. drawRoundRect ()

QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setBrush(QBrush(green));
painter.setPen(QPen(black));
painter.drawRoundRect(QRect(10, 10, 110, 70), 30, 30);

. 18.14. . 18.15.

drawEllipse () (. 18.15),
( 18.12).

18.12. drawEllipse ()

QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setBrush(QBrush(green, QBrush::CrossPattern));
painter.setPen(QPen(red, 3, QPen::DotLine));
painter.drawEllipse(QRect(10, 10, 110, 70));

drawChordO (. 18.16).
, ,
. ,
. .
()
. .
, ( 18.13).
18. 285

. 18.17. . 18.18.

18.13. drawChord()

QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setBrush(QBrush(Qt::yellow));
painter.setPen(QPen(Qt::blue));
painter.drawChord(QRect(10, 10, 110, 70), 45 * 16, 180 * 16);

(. 18.17).
. drawPieO
. .
( 18.14).

18.14. drawPieO

QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setBrush(QBrush(Qt::black, Qt::BDiagPattern));
painter.setPen(QPen(Qt::blue, 4));
painter.drawPie(QRect(10, 10, 110, 70), 90 * 16, 270 * 16)

drawPolygon() (. 18.18),
( 18.15).

18.15. drawPolygon ()

QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setBrush(QBrush(Qt::lightGray));
painter.setPen(QPen(Qt::black));

int n = 8;
QPolygonF polygon;
for (int i = 0; i < n; ++i) {
qreal fAngle =2 * 3.14 * i / n;
qreal x = 50 + cos(fAngle) * 40;
qreal = 50 + sin(fAngle) * 40;
polygon QPointF(x, y);
}
painter.drawPolygon(polygon);
286 IV.


QPicture ,
QPainter.
( ), ,
.
, . 18.16
myline.dat.

18.16.

QPicture pic;
QPainter painter;

painter.begin(&pic)
painter.drawLine(20, 20, 50, 50);
painter.end()

if (!pic.save("myline.dat")) {
qDebugO "can not save the file";
1

18.17
. drawPicture ( ) .
, ,
QPicture.

18.17.

QPicture pic;
if (!pic.load("myline.dat")) {
qDebugO "can not load the file";
1

QPainter painter;
painter.begin(this)
painter.drawPicture(QPoint(0, 0), pic);
painter.end()


QPainter
. ,
, (. 18.19).
, ,
. .
QPainter : translated, scaled,
18. 287

rotate shear . ,
. , ,
, ,
.

QPainter Qt
save ( ) restore ( ) .
QPainter. save ( ) ,
.
restore ( ) QPainter . :

pPainter->save();
pPainter->translate(20, 40);
pPainter->restore();

. QPainter
translated, .
,
Y.
,
.
,
. ,
20 10 :
QPainter painter;

painter.translate(20, 10);
288 IV.

scale ( )
: . ,
. ,
, :
QPainter painter;

painter.scale(1.5, 0.5);


. QPainter rotate ( ) ,
double, .
, .
, ( ) 30 :
QPainter painter;

painter.rotate(30.0);

.
,
QPainter shear ( ) .
. :
QPainter painter;

painter.shear(0.3, 0.0);


QPainter .
,
QPainter ;:setTransform().
,
,
QPainter , .
:
QTransform mat;
mat.scale(0.7, 0.5);
mat.shear(0.2, 0.5);
mat.rotate(15);
painter.setTransform(mat);
painter.drawText(rect(), Qt::AlignCenter, "Transformed Text");
18. 289

3x3:
Mil 12
21 22
Dx Dy

,
, 12, 21, 22, Dx Dy,
QTransform . . 18.3
. ,
QPainter translate ( 20 , 10 ) :
QTransform mat (1, 0, 0, 1, 20, 10);
painter. setTransform (mat) ;

18.3.

1 cos () 1

Ml 2 0 sin () 0

M21 0 -sin () 0

2 2 1 cos () 1

Dx 0 0 0

Dy 0 0 0

(painter path)
:
, .
, , ,
, QPainter: :drawPath() . 18.18
, : ,
(. 18.20).

18.18.

QPainterPath path;
QPointF ptl (width() , height () / 2) ;
QPointF pt2 (width () / 2, -height!) );
QPointF pt3 (width () / 2, 2 * height ());
QPointF pt4 (0, heightO / 2) ;
path . moveTo (ptl) ;
path.cubicTo (pt2, pt3, pt4);
290 IV.

QRect rect(width() / 4, height)) / 4, width)) / 2, height)) / 2);


path.addRect(rect);
path.addEllipse(rect);

QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setPen(QPen(Qt::blue, 6));
painter.drawPath(path);

. 18.20. . 18.21.

(
). ,
.
setClipRect ( ) . setClipRect ( ) .
18.19 (. 18.21).

18.19.

QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setClipRect (0, 0, 100, 100);
painter.setBrush(QBrush(Qt::green));
painter.setPen(QPen(Qt::black, 2));
painter.drawEllipse(0, 0, 200, 100);

QPainter::setciipRegion()
QPainter::setClipPath().
setciipRegion ( ) QRegion.
. ,
(10, 10),
, 100:
QRegion region(10, 10, 100, 100);
18. 291

, ,
:
QRegion region (10, 10, 100, 100, QRegion: :Ellipse) ;

,
. . :
QRegion region (QPolygon ( ) QPoint(0, 100)
QPoint(100, 100)
QPoint(100, 0)
QPoint(0, 0)
);

QRegion ,
united ( ) , intersected ( ) , subtracted ( ) xored ( ) :
united!) ,
;
intersected ,
;
subtracted ,
;
xored , ,
.
:
QRegion regionl(10, 10, 100, 100);
QRegion region2(10, 10, 100, 100, QRegion: :Ellipse) ;
QRegion region3 = regionl .subtract (region2) ;
painter. setClipRegion (region3) ;

(composition mode)

.
.
, , ,
. . 18.22.
QPainter: : setCompositionMode ( ) .
QPainter: :CompositionMode_
SourceOver.

,
- , ,
.
1 ( ) , 18.20,
,
. setFixedSizef)
,
rect.
292 IV.

(sourceimage) (resultimage) .
, QPainter::drawPolygon(),
, .
QPainter::drawEllipse ( ) ,
. QPainter::setCompositeMode () ,
1 ( ) mode, (sourceimage)
QPainter::drawimage ( ) .
QLabei::setPixmap ( )
. .

. 18.22.

18.20. main.cpp. 1 ()

QLabei* lbl(const QPainter::CompositionModes mode)


{
QLabei* plbl = new QLabei;
plbl->setFixedSize(100, 100);

QRect rect(plbl->contentsRect());
QPainter painter;

Qlmage sourceimage(rect.size(), Qlmage::Format_ARGB32_Premultiplied);


painter.begin(&sourceImage);
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setBrush(QBrush(QColor(0, 255, 0)));
painter.drawPolygon(QPolygon() rect.bottomLeft()
QPoint(rect.center().x(), 0)
rect.bottomRight ()
);
painter.end();

Qlmage resultimage(rect.size(), Qlmage::Format_ARGB32_Premultiplied);


painter.begin(sresultlmage);
18. 293

painter.setRenderHint(QPainter::Antialiasing, true);
painter.setCompositionMode(QPainter::CompositionMode_SourceOver);
painter.setPen(QPen(QColor(0, 255, 0), 4));
painter.setBrush(QBrush(QColor(255, 0, 0)));
painter.drawEllipse(rect);
painter.setCompositionMode(mode);
painter.drawlmage(rect, sourcelmage);
painter.end();

plbl->setPixmap(QPixmap::fromlmage(resultlmage));
return plbl;

, 18.21,
( 1 ( ) ) ,
.
(layout) (pgrd) (wgt).

18.21. main.cpp. man()

int main(int argc, char** argv)


{
QApplication app(argc, argv);
QWidget wgt;

//Layout Setup
QGridLayout* pgrd = new QGridLayout;
pgrd->addwidget(lbl(QPainter::CompositionMode_Source), 0, 0);
pgrd->addwidget(new QLabel("<CENTER>Source</CENTER>"), 1, 0);
pgrd->addwidget(lbl(QPainter::CompositionMode_SourceOver), 0, 1);
pgrd->addwidget(new QLabel("<CENTER>SourceOver</CENTER>"), 1, 1);
pgrd->addwidget(lbl(QPainter::CompositionMode_SourceIn), 0, 2);
pgrd->addwidget(new QLabel("<CENTER>SourceIn</CENTER>"), 1, 2);
pgrd->addWidget(lbl(QPainter::CompositionMode_SourceOut), 0, 3);
pgrd->addwidget(new QLabel("<CENTER>SourceOut</CENTER>"), 1, 3);
pgrd->addwidget(lbl(QPainter::CompositionMode_SourceAtop), 0, 4);
pgrd->addwidget(new QLabel("<CENTER>SourceAtop</CENTER>"), 1, 4);
pgrd->addwidget(lbl(QPainter::CompositionMode_Clear), 0, 5);
pgrd->addwidget(new QLabel("<CENTER>Clear</CENTER>"), 1, 5);
pgrd->addwidget(lbl(QPainter::CompositionMode_Destination), 2, 0);
pgrd->addwidget(new QLabel("<CENTER>Destination</CENTER>"), 3, 0);
pgrd->addwidget(lbl(QPainter::CompositionMode_DestinationOver), 2, 1);
pgrd->addwidget(new QLabel("<CENTER>DestinationOver</CENTER>"), 3, 1);
pgrd->addwidget(lbl(QPainter::CompositionMode_DestinationIn), 2, 2);
pgrd->addwidget(new QLabel("<CENTER>DestinationIn</CENTER>"), 3, 2);
pgrd->addwidget(lbl(QPainter::CompositionMode_DestinationOut), 2, 3);
pgrd->addWidget(new QLabel("<CENTER>DestinationOut</CENTER>"), 3, 3);
pgrd->addwidget(lbl(QPainter::CompositionMode_DestinationAtop), 2, 4);
pgrd->addwidget(new QLabel("<CENTER>DestinationAtop</CENTER>"), 3, 4);
pgrd->addwidget(lbl(QPainter::CompositionMode_Xor), 2, 5);
pgrd->addWidget(new QLabel("<CENTER>Xor</CENTER>"), 3, 5);
294 IV.

wgt.setLayout(pgrd);

wgt.show();

return app.execO;


,
QGraphicsitem (. 21).
setGraphicsEffeet ( ) .
QGraphicsEffect. : (blur),
(colorization), (drop shadow) (opacity).
, QGraphicsEffect
(. 18.23).
,
, QGraphicsEffect
draw ( ) , ,
. draw ( ) QPainter,
.
,
(. 22).
, 18.22 18.23
(. 18.24).
1(), 18.22,
. ,
setGraphicsEffeet () . ,
, , ,
.
.

18.22. main.cpp. 1 ()

QLabel* 1 (QGraphicsEffect* pge)


{
QLabel* plbl = new QLabel;
plbl->setPixmap(QPixmap(":/happyos.png"));

if (pge) {
plbl->setGraphicsEffect(pge);
}
return plbl;
}

, 18.23,
( pBlur, pshadow pCoiorize).
QFormLayout , .
18. 295

] 18.24 |D I

QGraphicsEffect

f QGraphicsBlurEffect

\ QGraphicsColorizeEffect

f QGraphicsDropShadowEffect |
| QGraphicsOpacityEffect

. 18.23. . 18.24.
: (Blur), (Drop Shadow)
(Colorize)

18.23. main.cpp. main ()

int main(int argc, char** argv)


{
QApplication app(argc, argv);
QWidget wgt;
QGraphicsBlurEffect* pBlur = new QGraphicsBlurEffect;
QGraphicsDropShadowEffect* pShadow = new QGraphicsDropShadowEffect;
QGraphicsColorizeEffect* pColorize = new QGraphicsColorizeEffect;

//Layout Setup
QFormLayout* pform = new QFormLayout;
pform->addRow("No Effects", lbl(O));
pform->addRow("Blur", 1 (pBlur));
pform->addRow("Drop Shadow", 1 (pShadow));
pform->addRow("Colorize", 1 (pColorize));
296 IV.

wgt.setLayout(pform);

wgt.show();

return app.exec( );
}

QPainter ,
QPaintDevice. QPainter , ,
, , (. 20) . QPainter
. ,
. .
QPicture, , ,
.
,
. ,
Qt, .
Qt : , .
.
,
.
QPainter
, , .
.
QRegion , .
,
.
.
, QGraphicsEffect,
.
19

,
. , .
,
, .


,
. Qt : PNG, BMP, ICO, TGA, TIFF,
XBM, XPM, PNM, JPEG, MNG, GIF, PNM, PBM, PGM PPM.
.

!

, ,
. , Windows
qgif.dll, qico.dll, qjpeg.dll, qtiff.dll, qtga.dll, qw.bmp
<MyApplication>/imageformats/. Linux ,
MacOSX macdeployqt, .
Windows windeployqt.
.

BMP
BMP (. Bit )
Windows.
,
.
. BMP
(API) Windows. BMP

, Qt
.
298 IV.

GIF
GIF (Graphics Interchange Format, )
.
,
LZW (Lempel-Ziv-Welch, : -
, ). GIF .
8-
, LZW-.

PNG
PNG (Portable Network Graphics, )
GIF ,
. PNG
PNG's Not GIF (PNG GIF). Web-
, ,
GIF. PNG ,
. GIF,
. ,
48 .


GIF
MNG, PNG.

JPEG
JPEG Joint Photographic Experts Group,
(, ),
. 1991 1993 .,
. ,
, , ,
,
.


(XPixMap) , XII (UNIX).
, , -
, .

.
24- .

, ,
.
Qt, -
19. 299

(. 3) ,

, , PNG JPEG.

. 19.1 ,
, , (),
{).

/* */
static const char* image_xpm[]
{
/* width height ncolors
charsj>erpixel */
"16 16 4 1",
" c #000000",
". c #848200",
"+ c #848284",
"0 c #d6d3ce" ,

"0 0
. @@@@@@@@ @ +'
"0 +'
"0 @@@@@@@0 . + '
@@@@@@@0 + '
"0 . @@@@@@@0 . +'
"0 . @0000000
@@@@@@@0 . +T
"0 . . . . +'
"0 +*
. +'
"0 .. 00 . +'
"0 .. 00 . +'
"0 .. @0 . +'
"@@ +'
" @0++++++++++++++
};

. 19.1.

/**/, .
image_xpm, .

( 16x16 ).
( 4).
.
, #,
RGB (
HTML). ,
color ().

s,
. , , None,
.

. 19.1 ,
, -
, -
@.
.
300 IV.

-
-
, , ,
. ,
,
.

Qlmage
Qlmage -
. QPaintDevice,
, QPainter.
Qlmage , . 19.1.

19.1. Format Qlmage


Format Invalid
Format Mono .
,

Format MonoLSB .
,

Format Index8
8- (. 17)
Format_RGB32 .
-
OxFF,
Forma t_ARGB32 32
Format ARGB32 Premultiplied Format ARGB32,
Qlmage

format () .
convert ToFormat ( ) ,
Qlmage.
, ,
. ,
320 240 32 .
Qlmage img(320, 240, Qlmage: : Forma t_RGB32) ;

Qlmage ,
, Qlmage.
Qt,
, . :
Qlmage img ( "lisa . jpg" ) ;
19. 301

. ,
, . 19.1, :
#include "image_xpm.h"

Qlmage img(image_xpm);

load().
,
. ,
.
unsigned char*,
: GIF, BMP, JPG, , PNG.
, Qimage
. :
Qlmage img;
img.load("lisa.jpg");

save()
Qimage . , ,
. :
Qlmage img(320, 240, 32, QColor::blue);
img.save("blue.jpg", "JPG");


, Unisys LZW,
GIF, GIF
. Qt
GIF.

Qimage ,
. RGB- ( X , Y)
pixel(, ). RGB-
QRgb (. 17). :
QRgb rgb = img.pixel(250, 100);


pixeiindex ( ) (. 17) (X,
). ,
8 .

(X, Y) RGB-
setPixel(x, , rgb).


, 8 , rgb
(. 17),
setColor().

:
QRgb rgb = qRgb(200, 100, 0);
img.setPixel(20, 50, rgb);
302 IV.

Qimage ,
.


(. . 19.1).
, ,
, .
Qimage , .

scanLineO ,
, . ,
0 , .
( 19.1-19.3),
brightness ( ) ,
. . 19.2.

E 19-2 = I El H-S.-,!

f r 0
1 )

. 19.2. /

brightness!) ( 19.1) :
, .
( imgTemp).
.
width!) height!). 0 height!).
scanLine ( ) tempLine.
width ( ) .
, qRed ( ) , qGreen ( ) , qBlue ( )
RGB , ( ).
- .
, g, b . ,
(tempLine), QRgb, qRgba ( )
,
0 255.
.
imgTemp.

19.1. brightness ()

Qimage brightness (const Qlmages imgOrig, int n)


{
Qimage imgTemp = imgOrig;
qint32 nHeight = imgTemp. height () ;
qint32 nWidth = imgTemp . width () ;
19. 303

for (qint32 = 0; < nHeight; ++) {


QRgb* tempLine = reinterpret_cast<QRgb*>(imgTemp.scanLine());

for (qint32 x = 0; x < nWidth; ++x) {


int r = qRed(*tempLine) + n;
int g = qGreen(*tempLine) + n;
int b = qBlue(*tempLine) + n;
int a = qAlpha(*tempLine);

tempLine++ = qRgba(r > 255 ? 255 r < 0 ? 0 r


g > 255 ? 255 g < 0 ? 0 g
b > 255 ? 255 b < 0 ? 0 b
a

return imgTemp;
}

( 19.2)
happyos.png , .
setPixmapO ,
brightness .
addwidget().

19.2. man()

int main(int argc, char** argv)


{
QApplication app(argc, argv);
Qlmage img(":/happyos.png");
QWidget wgt;

QHBoxLayout* phbx = new QHBoxLayout;


phbx->setMargin(0);
phbx->setSpacing(0);

for (int i = -150; i < 150; i += 50) {


QLabel* plbl = new QLabel;
plbl->setFixedSize(img.size());
plbl->setPixmap(QPixmap: rfromlmage(brightness(img, i)));
phbx->addwidget(plbl);
1

wgt.setLayout(phbx);
wgt.show();

return app.exec();
304 IV.

Qimage QPainter::
drawimage ( ) . Qimage , drawimage ( )
- ( QPixmap). 19.3
(0, 0) (. 19.3).

19.3.

QPainter painter (this) ;


Qimage img(" : /lisa.jpg" ) ;
painter .drawimage (0, 0, img);

. 19.3. Qimage . 19.4. Qimage


,
drawimage (). 19.4
, (30, 30)
1 10, 100 (. 19.4).

19.4.

QPainter painter (this) ;


Qimage img (": /lisa. jpg ) ;
painter .drawimage (0, 0, img, 30, 30, 110, 100);

invertPixels Qimage: zinvertRgb,


. Qimage : : invertRgba
, -. 19.5
, . 19.5.
19. 305

19.5.

QPainter painter(this);
Qlmage img(":/lisa.jpg");
painter.drawlmage(0, 0, img);
img.invertPixels(Qlmage::InvertRgb);
painter.drawlmage(img.width(), 0, img);

. 19.5.

scaled
. Qt : : IgnoreAspectRatio Qt::KeepAspectRatio,
, 17. 19.6
,
. 19.6.

19.6.

QPainter painter(this);
Qlmage imgl(":/lisa.jpg");
painter.drawlmage(0, 0, imgl);

Qlmage img2 =
imgl.scaled(imgl.width() / 2, imgl.height(), Qt::IgnoreAspectRatio);
painter.drawlmage(imgl.width(), 0, img2);

Qlmage img3 =
imgl.scaled(imgl.width(), imgl.height() / 2, Qt::IgnoreAspectRatio);
painter.drawlmage(0, imgl.height(), img3);
306 IV.

Qlmage img4 =
imgl.scaled(imgl.width() / 2, imgl.height(), Qt::KeepAspectRatio);
painter.drawImage(imgl.width(), imgl.height(), img4);

. 19.6.

Qlmage
. mirrored
, .
mirrored , ,
. 19.7 , .
. 19.7.

19.7.

QPainter painter(this);
Qlmage img(":/lisa.jpg");
painter.drawlmage(0, 0, img);
painter.drawlmage(img.width(), 0, img.mirrored(true, true));
19. 307

. 19.7.

Qlmage
, Qimage .
,
. Qimage
32-, . .
: Qimage::Format_ARGB32 Qimage::FormatARGB32_Premultiplied. Qimage::
FormatARGB32_Premultiplied ,
. 19.8.
. 19.8
.
19.8 paintEventO
Qimage , size ( ) .

. 19.8.
308 IV.

QPainter begin Qimage


. initFromO
, , , . . setRenderHint()
QPainter::Antialiasing, true
, (false , ).
eraseRecto , .
, rect().
drawEilipse ( ) . end()
Qimage
. begin ( ) . ,
drawimage ( ) Qimage .

19.8. Qimage

void ImageDraw::paintEvent(QPaintEvent* pe)


{
Qimage img(size(), Qimage::Format_ARGB32_Premultiplied);
QPainter painter;

painter.begin(&img);
painter.initFrom(this);
painter.setRenderHint(QPainter::Antialiasing, true);
painter.eraseRect(rect());
painter.drawEilipse(0, 0, size().width(), size().height());
painter.end();

painter.begin(this);
painter.drawimage(0, 0, img);
painter.end();
)

-
-
, -,
. -
QPainter.
, ,
() , ,
.

QPixmap
QPaintDevice.
QPixmap. ,
.
, ,
QPixmap, ,
QPainter, .
19. 309

.
:
QPixmap pix(320, 240);

QPixmap
.
QPixmap : : def aultDepth ( ) .
. :
QPixmap pix (": /forest . jpg" ) ;

QPixmap, Qimage,
:
# include "image_xpm.h"

QPixmap pix ( image_xpm) ;

QPixmap , ,
.
.
Qimage.

QPainter
: load save .
Qimage ( ).
QPainter: :
QPixmap
drawPixmap ( ) . 19.9
drawPixmap ( ) . ,
. ,
. . 19.9.

. 19.9. QPixmap
310 IV.

19.9.

QPainter painter(this);
QPixmap pix(":/forest.jpg");
painter.drawPixmap(0, 0, pix);

QRect r(pix.width(), 0, pix.widthO / 2, pix.height());


painter.drawPixmap(r, pix);

QPixmapCache
QPixmap.
, .
insert ( ) QPixmap .
,
. - find ( ) ,
. ,
,
.

QBitmap
QBitmap QPixmap QBitmap.
,
, . ,
: Qt::color0 Qt::colori. (bi-level).
.

QPixmap
QPixmap ,
, QPixmap::setMask().
, , .
QBitmap.
QPainter, colorO,
colori. ,
. ,
.
( 1 9.1 0) ,
(. 19.10).
19.10 paintEvent .
QPixmap,
( size ).
pix begin ( ) . drawPixmap()
pix stein.jpg,
end().
19. 311

. 19.10.

bmp,
. fill ()
Qt: icolorO ( ). ,
Qt::color1, , , ,
, .
pix setMaskO,
.

19.10.

QPixmap pix(size());
QPainter painter;

painter.begin(&pix);
painter.drawPixmap(rect(), QPixmap(":/stein.jpg"));
painter.end();

QBitmap bmp(size());
bmp.fill();

painter.begin(sbmp);
painter.setPen(QPen(Qt::colorl));
painter.setFont(QFont("Times", 75, QFont::Bold));
painter.drawText(rect(), Qt::AlignCenter, "Draw Text");
painter.end();

pix.setMask(bmp);

painter.begin(this);
painter.drawPixmap(rect(), pix);
painter.end();


QWidget, QPixmap, setMask ( ) .
, .
( 19. 1 1), . 19.1 1 .
312 IV.

. 19.11.

19.1 1 window. pix


. setPixmapO ,
, window QLabei.

19.11. main.cpp. maln()

int main(int argc, char** argv)


{
QApplication app(argc, argv);
Window win;
QPixmap pix(:/images/unixoids.png");

win.setPixmap(pix);
win.setMask(pix.mask());
win.show();

return app.exec();
}

, GIF, PNG XMP,


. load ( ) ,
setMask().
, QLabei
Qt::FramelessHint.
. window ( 19.12)
mousePressEvent ( ) mouseMoveEvent ( ) ,
, . m ptPosition
.
19. 313

19.12. main.cpp

class Window : public QLabel {


private:
QPoint m_ptPosition;

protected:
virtual void Window::mousePressEvent(QMouseEvent* pe)
{
m_ptPosition = pe->pos();
}

virtual void Window::mouseMoveEvent(QMouseEvent* pe)


{
move(pe->globalPos() - m_ptPosition);
}

public:
Window(QWidget* pwgt = 0)
: QLabel(pwgt, Qt::FramelessWindowHint | Qt::Window)
{
}
};

, ,
: QPixmap createHeuristicMask(),
, .
,
.
,
. ,
.
, .
. setAttribute()
Qt::WA_TranslucentBackground.
( 19.13),
. 19.12. .
.

. 19.12.


314 IV.

19.13 (1)
, .
Qt::WA_TranslucentBackground. ,
, .
, 16x16 , ,
,
clicked () QCoreApplicaion::quit ( ) .
(
pvbx).

19.13. main.cpp. Window

int main(int argc, char** argv)


{
QApplication app(argc, argv);
QLabel 1;

1 .setWindowFlags(Qt::Window I Qt::FramelessWindowHint);
1 .setAttribute(Qt::WA_TranslucentBackground);
1 .setPixmap(QPixmap(": /happyos.png"));

QPushButton* pcmdQuit = new QPushButton("X");


pcmdQuit->setFixedSize(16, 16);
QObject connect(pcmdQuit, SIGNAL(clicked()), &app, SLOT(quit()));

//setup layout
QVBoxLayout* pvbx = new QVBoxLayout;
pvbx->addWidget(pcmdQuit);
pvbx->addStretch(l);
1.setLayout(pvbx);

1 .show();

return app.exec();
1

Qt .
, BMP, GIF, PNG, JPEG, XPM .
.
, .
Qt -
-.
- Qimage.
Qimage , ,
.
19. 315

,
. Qimage ,
, : ,
, . QPainter
Qimage , , . .
- QPixmap.
Qimage.
QPixmap QPainter.
, .
QPixmap QBitmap
.
20

, ,
, , ,
, .
,

. ,
.
. ,
. ,
. ().
( ).
.
.
,
.

.
Qt QFont .
:
;
;
;
;
.
QFont QWidget: : set Font ()
, .
, QFont
QApplication: :set Font ( ) .
Qt : QFontDataBase, QFontinfo
QFontMetrics:

QFontDatabase
. families (),
QStringList. QFontDatabase
stylestring ( ) QFontinfo;
20. 317

QFontinfo .
family . italic bold
, ( ) ;
QFontMetrics ,
. 20.1.

leftBearing()


rightBearing()

width(QChar)

ascentQ
height()


width(QString) descent)) lineSpacing()



. 20.1.

QFontMetrics QFont,
. leftBearing( ) rightBearing( )
. linespacing ()
. width(const QStrings, int len)
, , ,
.
width().
height . :
( )

QFontMetrics fm(QFont("Courier", 18, QFont::Bold));


QString str = "String";
qDebugO "Widht:" fm.width(str)
"Height:" fm.height();

ascent () descent!) .
(
), ,
.
boundingRect ( ) , QRect,
, .
318 IV.


QPainter QPainter::setFont ()
QFont. QPainter 7 drawText ( )
, :
drawText(int , int , const QStrings str)
psz.
,
;
drawText(const QPoints pt, const QStrings psz, int nLen = -1)
,
QPoint. nLen ,
. -1 ,
.
20.1 Draw Text (. 20.2).

20.1. setFont() drawText()

QPainter painter(this);
painter.setFont(QFont("Times", 25, QFont::Normal));
painter.drawText(10, 40, "Draw Text");

_ DrawText
[a | l]
"

. 20.2.
Draw Text
QPainter
drawText()idrawText(const QRect& , int flags, const QStrings str)
str .
flags .
, . 7.1 20.1,
| ().

20.1. TextFlag Qt


TextSingleLine 0x0100 ( \)
TextDontClip 0x0200 , ,
,
TextExpandTabs 0x0400 \t
TextShowMnemonic 0x0800 & ,

20. 319

20.1 ()


TextWordWrap 0x1000 ,

20.2 (. 20.3).

, ,
Textwordwrap .
drawRect ( )
.

. 20.3.

20.2. setFont()y drawRect () drawText ()

QPainter painter (this) ;


QRect r(0, 0, 120, 200);
.
painter set Font (QFont ("Times", 25, QFont: : Normal) ) ;
painter .drawRect (r);
painter .drawText (r, Qt : :AlignCenter | Qt ::TextWordWrap, "Draw Text");

. 20.4. ,

(. 18), . 20.4.
( )
QGradient : : setColorAt ( ) ,
:
QLinearGradient gradient (0, 0, 500, 0) ;
.
gradient setColorAt ( 0 , Qt :: red) ;
.
gradient setColorAt (0.5, Qt : : green) ;
.
gradient setColorAt (1, Qt : : blue ) ;

QPen.
QPainter setPen()n
set Font ( ) , drawText ( ) :
320 IV.

QPainter painter(this);
painter.setPen(QPen(gradient, 0));
painter.set Font(QFont("Times", 50, QFont::Normal));
painter.drawText(60, 60, "Gradient Text);

, , ,
. , ,
. , ,
, .
elidedTextO QFontMetrics ( 20.3). . 20.5
, ,
, , .


_
This is a lon...ze the window

. 20.5.

20.3.

#include <QtWidgets>

// =====================================================================
class ElidedText : public QWidget {
protected:
virtual void paintEvent(QPaintEvent*)
{
QString str = "This is a long text. Please, resize the window";
QString strElided =
fontMetrics().elidedText(str, Qt::ElideMiddle, width());
QPainter painter(this);
painter.drawText(rect(), strElided);
}

public:
ElidedText(QWidget* pwgt = 0) : QWidget(pwgt)
{
}
};

//
int main(int argc, char** argv)
{
QApplication app(argc, argv);
ElidedText et;
et.resize(200, 20);
et.show();

return app.exec();
20. 321

20.3 paintEvent () ( str).


elideText ,
Qt::ElideMiddle (
. 20.2). ,
drawText().

20.2. TextElideMode Qt


ElideLeft 0x0000
ElideRight 0x0001
ElideMiddle 0x0002
ElideNone 0x0003

.
, , ().
QFont .
QFontinfo .
QFontDataBase , .
QFontMetrics ,
, .
QPainter , ,
. , , .
21

. ...
! , .
,

,
.
.
.
,
/ . ,
(collision detection). ,
QTableWidget, QTreeWidget QListWidget (. 11), ,
- (Model-View) (. 12).

QObject QPaintDevice

QWidget

QFrame
3
QAbstractScroMAreaJ
~| QGraphicsView |
[ QGraphicsScene
. 21.1.

:
QGraphicsScene
QGraphicsView (. 21.1),
QGraphicsltem (. 21.2).
: QGraphicsScene
,
QGraphicsltem, QGraphicsView ,
QAbstractScroiiArea. (
QGraphicsScene),
(. 21.3).
21. 323

QGraphicsItenJ
QAbstractGphicsShapeltemJ

D
[ QGraphiesRectltem
D
IGphicsPolygonltemJ

"GphicsItemGroufj
[QGpfdicsLineltem J
_
QGraphicsObject

[ QGraphicsTextltem QDeclarativeParserStatus

f QDeclarativeltem
[ QGraphicsSvgltem QGraphicsLayoutltem

QGraphicsWidget
_

JOGphicsWebVieJ
. 21.2.

_ TreeWidget _ Tree Widget

m ft *
! 1 2

\ t /

-
. 21.3.
324 IV.

(QGraphicsScene)
. - ,
QGraphicsScene .
, ,
.
.
changed ( )
, .
(QGraphicsScene) , ,
, QGraphicsitem (. . 21.2).
.
QGraphicsScene : : addltem ( ) .
addEllipse ( ) ,
addLineO, addPathO, addPixmapO, addPolygon ( ) , addRectO addTextf),
, .
,
QGraphicScene : : items ().
, QGraphicScene: :itemAt(),
, .
QGraphicsScene
QRectF.
.

QGraphicsview ,
(QGraphicsScene).
(QGraphicsScene)
QGraphicsview. , QGraphicsview
QAbstractScrollArea, ,
. , QGraphicsScene,
.
, .
QGraphicsview ,
.
,
.
,
QGraphicsview: : centerOn ( ) , .
, , QGraphicsview
QAbstractScrollArea,
(viewport) . Qwidget
QGLWidget (. 23)
. -
21. 325

QAbstractScrollArea::setviewPort ( ) . ,
, OpenGL,
:
pView->setViewport(new QGLWidget);

, setMatrixf),
, .

QGraphicsitem (. . 21.2).
, (drag & drop),
(collision detection).
:
setPos ( ) ;
: hide ( ) show ( ) ;
/ setEnable ( );
: rotate ( ) , scale ( ) , translate ( ) , shear ( ) setMatrix ( ) ;
paint ( ) .
, .
(. . 21.2)
, QGraphicsitem
paint() boundingRect( ).
, QAbstractGraphicsShapeitem,
: (QGraphicsEilipseitem),
(QGraphicsPolygonltem), (QGraphicsRectltem) (QgraphicsSimple-
Textitem). - , ,
, QAbstractGraphicsShapeitem.
, . 21.2
. QGraphicsSimpleTextltem QGraphicsTextltem.
QGraphicsSimpieTextitem
. ,
QGraphicsTextltem,
, .
(GraphicsLineitem),
(QGraphicsPixmapItem), (QGraphicsSvgltem).
QGraphicsitemGroup .
21.1 (. 21.4).
QGraphicsScene QGraphicsView.
view scene,
QGraphicsView: :setScene ( ) .
( pRectitem)
QGraphicsScene, .
QGraphicsScene : : additem ( ) . setPen ( )
326 IV.

. ,
, setBrush ( ) . setRect ( )
. QGraphicsScene::
addPixmap(), QGraphicsScene::addText ( ) QGraphicsScene::addLine ( )
, .

. 21.4. ,

,
setFlagsO QGraphicsitem::
ItemlsMoveable.
, show()
.

21.1. main.cpp

#include <QtWidgets>

int main(int argc, char** argv)


{
QApplication app(argc, argv);
QGraphicsScene scene(QRectF(-100, -100, 300, 300));
QGraphicsView view(sscene);

QGraphicsRectltem* pRectltem =
scene.addRect(QRectF(-30, -30, 120, 80),
QPen(Qt::black),
QBrush(Qt::green)
);
pRectItem->setFlags(QGraphicsitem::ItemlsMovable);

QGraphicsPixmapItem* pPixmapItem =
scene.addPixmap(QPixmap(":/haus.jpg"));
pPixmap!tem->setFlags(QGraphicsitem::ItemlsMovable);
21. 327

QGraphicsTextltem* pTextltem =
scene.addText("Move us with your mouse");
pTextItem->setFlags(QGraphicsItem::ItemlsMovable);

QGraphicsLineltem* pLineltem =
scene.addLine(QLineF(-10, -10, -80, -80), QPen(Qt::red, 2));
pLineItem->setFlags(QGraphicsItem::ItemlsMovable);

view.show();

return app.exec();

, , ,
. -
, :
QGraphicsLineltem* pLineltem =
scene.addLine(QLineF(-10, -10, -80, -80), QPen(Qt::red, 2));
QGraphicsTextltem* pTextltem = scene.addText("Child");
pTextItem->setParentItem(pLineltem);
,
, , ,
, :
QGraphicsTextltem* pTextltem = scene.addText("Shear");
pTextItem->shear(-0.5, 0.0);
,
.
QGraphicsItem .
QGraphics::shape( ) QGraphicsItem::
collideswitho . ,
QGraphicsItem::shape () .
. QGraphicsItem
.

, .
QGraphicsView QAbstractScrollArea,
. ,
. ,
. , ,
QGraphicsView::scene(), ,
, .
- ,
. , .


. :
328 IV.

, ,
, .
, ,
. . . 21.5
, .

QEvent

QGraphicsSceneEvent

[ QGraphicsSceneContextMenuE vent |
f QGraphicsSceneQragOropEvent
[ QGraphicsSceneHelpEvent
[ QGraphicsSceneHoverEvent
[ QGraphicsSceneMouseEvent
[ QGraphicsSceneWhelEvent

. 21.5.

, , ,
(QGraphicsHoverEvent)
(QGraphicsContextMenuEvent).
(drag & drop).
, ,
setAcceptDrops ( ) .
dragEnterEvent( ) , dragMoveEvent(), dragLeaveEvent( ) dropEvent ( ).
, QDrag,
, .
,
- . ,
QGraphicsSceneEvent::widget ( ) .
.
( 21.2-21.4),
. 21.6. :
;
;
;
.
21.2 Myview,
QGraphicsView. Myview ,
,
(. 21.4).
21. 329

. 21.6. ,

21.2. MyView.h

#pragma once

#include <QGraphicsView>

// ================================================
class MyView: public QGraphicsView {
Q_OBJECT
public:
MyView(QGraphicsScene* pScene, QWidget* pwgt = 0)
: QGraphicsView(pScene, pwgt)
{
}

public slots:
void slotZoomln()
{
scale(1.1, 1.1);
}

void slotZoomOut()
{
scaled / 1.1, 1 / 1.1);
}
330 IV.

void slotRotateLeft()
{
rotate(-5);
}

void slotRotateRight()
t
rotate(5);
}

simpieitem, 21.3,
. boundingRect ( )
, .
, ,
(penwidth).
paint ( ) . ,
3 .
QPainter setPenO,
save ,
restore().

mousePressEvent ( ) ,
, , ,
mousePressEvent ( )
.
mouseReleaseEvent ( ) .

mouseReieseEvent ( ) .

21.3. main.cpp. Simpieitem

class Simpieitem : public QGraphicsItem {


private:
enum (nPenWidth = 3};

public:
virtual QRectF boundingRect() const
(
QPointF ptPosition(-10
nPenWidth, -10
nPenWidth);
QSizeF size(20 + nPenWidth * 2, 20 + nPenWidth * 2);
return QRectF(ptPosition, size);
}

virtual void paint(QPainter* ppainter,


const QStyleOptionGraphicsItem*,
QWidget*
)
21. 331

{
ppainter->save();
ppainter->setPen(QPen(Qt::blue, nPenWidth) );
ppainter->drawEllipse(-10, -10, 20, 20);
ppainter->restore();
}

virtual void mousePressEvent(QGraphicsSceneMouseEvent* pe)


(
QApplication::setOverrideCursor(Qt::PointingHandCursor);
QGraphicsItem: imousePressEvent(pe);
}

virtual void mouseReleaseEvent(QGraphicsSceneMouseEvent* pe)


(
QApplication::restoreOverrideCursor();
QGraphicsItem::mouseReleaseEvent(pe);
}

main(), 21.4, (scene),


( pview), ( pSimpleitem pPixmapitem) ,
( pcmdRotateLeft pcmdRotateRight),
( pcmdzoomin pcmdzoomOut ).
setRenderHint ( )
, (
).
simpieitem
QGraphicsScene::additem ( ) , setPosO .
,
setFlags ( ) QGraphicsItem::itemisMovable.
( pPixmapitem)
setParent () , ,
simpieitem. setFlags
. , ,
-. , ,
, ,
,
, .

Myview, QVBoxLayout
wgt.

21.4. main.cpp. main()

int main(int argc, char** argv)


{
QApplication app(argc, argv);
332 IV.

QWidget wgt;
QGraphicsScene scene(QRectF(-100, -100, 640, 480));

MyView* pView = new MyView(sscene);


QPushButton* pcmdZoomln = new QPushButton("&Zoom In");
QPushButton* pcmdZoomOut = new QPushButton("Z&oom Out");
QPushButton* pcmdRotateLeft = new QPushButton("SRotate Left");
QPushButton* pcmdRotateRight = new QPushButton("Ro&tate Right");

pView->setRenderHint(QPainter::Antialiasing, true);

Simpleltem* pSimpleltem = new Simpleltem;


scene.addltem(pSimpleltem);
pSimpleItem->setPos(0, 0);
pSimpleItem->setFlags(QGraphicsItem::ItemlsMovable);

QGraphicsPixmapItem* pPixmapItem =
scene.addPixmap(QPixmap(":/haus2.jpg"));
pPixmapItem->setParentItem(pSimpleltem);
pPixmapItem->setFlags(QGraphicsItem;:ItemlsMovable);

QObject;:connect(pcmdZoomln, SIGNAL(clicked()),
pView, SLOT(slotZoomln())
);
QObject::connect(pcmdZoomOut, SIGNAL(clicked()),
pView, SLOT(slotZoomOut())
);
QObject::connect(pcmdRotateLeft, SIGNAL(clicked()),
pView, SLOT(slotRotateLeft())
);
QObject::connect(pcmdRotateRight, SIGNAL(clicked()),
pView, SLOT(slotRotateRight())
);

//Layout setup
QVBoxLayout* pvbxLayout = new QVBoxLayout;
pvbxLayout->addWidget(pView);
pvbxLayout->addWidget(pcmdZoomln);
pvbxLayout->addWidget(pcmdZoomOut);
pvbxLayout->addWidget(pcmdRotateLeft);
pvbxLayout->addWidget(pcmdRotateRight);
wgt.setLayout(pvbxLayout );

wgt.show();

return app.exec( );
21. 333


QGraphicsScene
, , , ,
,
. , ,
,
, ,
.

.

(. 21.7).

( 21.5) (scene)
(view). Quit
addwidget(), QGraphicsProxyWidget.
,
QTransform. translate () ,
rotate ( ) scale( ) . rotate ( )
, , ,

, Y (Qt::YAxis).
( pproxywidget) setTransformO .
QDial QProgressBar. -
, , , Quit
quit ( ) , valueChanged ( ) Qdial setvalue( )
QProgressBar.
334 IV.

15 Z. , ,
, .

21.5. . main.cpp

#include <QtWidgets>

int main(int argc, char** argv)


{
QApplication apptargc, argv);
QGraphicsScene scene(QRectF(0, 0, 400, 400));
QGraphicsView view(sscene);

QPushButton cmd("Quit");
QGraphicsProxyWidget* pproxyWidget = scene.addwidget(&cmd);
QTransform transform = pproxyWidget->transform();

transform.translate(100, 350);
transform.rotate(-45, Qt::YAxis);
transform.scale(8, 2);
pproxyWidget->setTransform(transform);
QObject::connect(&cmd, SIGNAL(clicked()), &app, SLOT(quit()));

QDial dia;
dia.setNotchesVisible(true);
pproxyWidget = scene.addwidget(&dia);
transform = pproxyWidget->transform();

transform.scale(4, 2);
transform.rotate(-45, Qt::YAxis);
pproxyWidget->setTransform(transform);

QProgressBar prb;
prb.setFixedSize(500, 40);
pproxyWidget = scene.addwidget(&prb);
transform = pproxyWidget->transform();

transform.translate(20, 200);
transform.scale(2, 2);
transform.rotate(80, Qt::YAxis);
transform.rotate(30, Qt::XAxis);
pproxyWidget->setTransform(transform);

QObject;:connect(&dia, SIGNAL(valueChanged(int )),


sprb, SLOT(setValue(int))
);

view.rotate(15);
view.show();

return app.exec();
21. 335

,
,
. QGraphicsScene, QGraphicsView, QGraphicsItem
,
. -
. QGraphicsScene
QGraphicsView.
QGraphicsScene ,
.
,
.
, QGraphicsItem,
, , ,
. .
. (QGraphicsItem)
QGraphicsScene.
22

.
. ,
.
, .
,
.

QMovie
QPixmap,
. QMovie,
.
QPixmap Qimage. MNG
GIF. , , ,
27, QtMultimedia, , .
QMovie .
.
.
: setPaused(bool),
setSpeed(), stop( ) start().
setPausedo true ,
false .
stateChanged ( ) .
QMovie::start ( ) , a stop ( ) .
state(),
:
QMovie : : Paused , ;
QMovie : : Running , ;
QMovie : : NoRunning .
22. 337

,
frameCount () . ,
currentPixmapO current image () ,
QPixmap Qlmage.
QLabel. QLabel
setMovie ( ) , .
, 22.1, (. 22.1).

. 22.1.

22.1, 3 : (),
(lbi) (mov),
motion. mng. setMovie ()
. resize () , .
( show ( ) ) start { ) .

22.1. main.cpp

# include <QtWidgets>

int main(int argc, char** argv)


{
QApplication app(argc, argv);
QLabel lbl;
QMovie mov mot i on . mng" ) ;

.
lbl setMovie ( &mov) ;
.
lbl resize (328, 270);
.
lbl show ( ) ;
mov. start ( ) ;

return app . exec ( ) ;


338 IV.

SVG-
SVG (Scalable Vector Graphics).
2001 W3C (World Wide Web
Consortium).
XML ,
. SVG
Web-.
Qt QtSvg. ,
( pro)
, QT += svg. SVG-
QSvgwidget. SVG-
QSvgwidget, load ( ) . load ( ) ,
, QByteArray.
QSvgRenderer,
, , ,
, . QSvgRenderer
Qimage QGlwidget.
22.2
QSvgwidget (. 22.2). QSvgwidget
SVG- motion.svg, .
show ( ) , . repaintNeeded ( )
QSvgRenderer repaint QSvgwidget ,
QSvgwidget.

. 22.2.
22. 339

22.2. main.cpp

#include <QtWidgets>
# include <QtSvg>

int main(int argc, char **argv)


{
QApplication app(argc, argv);

QSvgWidget svg ( ":/motion.svg");


svg.show ();

QObject::connect (svg.Tenderer(), SIGNAL(repaintNeeded ( ) ),


&svg, SLOT(repaint () )
);

return app.exec ();


}


Qt ,
, , , , ,
. . Qt
, ,
( 34).
,
QTimer, QTimeLine QGraphicsItemAnimation.

.
,
,
.
.
Graphicsview.
, . 22.3.
QAbstractAnimation ,
, start ( ), stop( ) pause ( )
, . stateChanged ( )
, .
QAbstractAnimation : QVariantAnimation,
QAnimationGroup QPauseAnimation. Variant QVariantAnimation
, , , ,
, .
QVariantAnimation QPropertyAnimation,
, .

(. 22.4), ( 22.3).
340 IV.

addAnimation
i>)fQAbstrctAmmatiorJ
QTransition
[[QPauseAnimation j
fQAnimationGroup J
addTransition()

QState

QVariantAnimation
J
|QPropertyAnimation 1
:

QObject
Graphics Object

. 22.3. . 22.4.

22.3 QLabel
setPixmapO .
(. 18) setGraphicsEffect () .
(anim)
effect, "color",
. setstartvalue ( ) ,
setKeyValueAt ( ) 0 1,
setEndValue ( )
.

,
.
, ,
.

setDuration ( )
. 3000 , , 3 .
setLoopCount ( ) ,
, ,
. , start ( ) .

22.3. main.cpp.

#include <QtWidgets>

int main(int argc, char** argv)


{
QApplication app(argc, argv);
QLabel lbl;
22. 341

1 .setPixmap(QPixmap (":/happyos.png" ));

QGraphicsColorizeEffect effect;
lbl.setGraphicsEffect (seffect);

QPropertyAnimation anim(&effeet, "color");


anim.setStartValue(QColor(Qt ::gray) );
anim.setKeyValueAt(0.25f, QColor(Qt::green) );
anim.setKeyValueAt (0.5f, QColor(Qt::blue) );
anim.setKeyValueAt (0.75f, QColor(Qt::red) );
anim.setEndValue(QColor(Qt ::black) );
anim.setDuration(3000);
anim.set LoopCount (-1);
anim.start ();

lbl.show ( );

return app.exec ();


}

QAnimationGroup.
. ,
, QObject.
. ,
. , ,
, . ,
, .
, ,
22.4.

22.4.

QParallelAnimationGroup* pgroupl = new QParallelAnimationGroup;


pgroupl->addAnimation(paniml);
pgroupl->addAnimat ion(panim2 );
QSequentialAnimationGroup* pgroup2 = new QSequentialAnimationGroup;
pgroup2->addAnimation(panim3);
pgroup2->addAnimation(panim4 );
pgroup2->addAnimation(panim5);
pgroup2->addAnimation(groupl);

pgroup2->start ();

22.4 ( QParallelAnimationGroup)
addAnimationO : paniml
panim2. ( QSequentialAnimationGroup)
, addAnimationO
, . start ( )
.
342 IV.


,
. (Easing Curves)
,

. (
22.5), (. 22.5).

=> 111 2
_
, -Wiru-).Wrf? -
I ' ED
2
-
*

' cn : ED 2
L!rJ
-
(=)

i1 0 2
[Animated Window2

. 22.5.

22.5 (lbil 12)


( paniml panim2).
"geometry" , "pos"
.
, ( setDurationO).
setstartvalue ( ) setEndValue ( )
. QRect,
QPoint. setEasingCurve ()
. , :
inOutExpo OutBounce. , ,
( group).
addAnimationO (
setLoopCount ( ) ). , start ( )
.

22.5.

iinclude <QtWidgets>

int main(int argc, char** argv)


22. 343

QApplication app(argc, argv);


QLabel lbll("Animated Windowl");
QLabel lbl2("Animated Window2");

QPropertyAnimation* paniml =
new QPropertyAnimation(slbll, "geometry");
paniml->setDuration(3000);
paniml->setStartValue(QRect(120, 0, 100, 100));
paniml->setEndValue(QRect(480, 380, 200, 200));
paniml->setEasingCurve(QEasingCurve::InOutExpo);

QPropertyAnimation* panim2 = new QPropertyAnimation(&12, "pos");


panim2->setDuration(3000);
panim2->setStartValue(QPoint(240, 0));
panim2->setEndValue(QPoint(240, 480));
panim2->setEasingCurve(QEasingCurve::OutBounce);

QParallelAnimationGroup group;
group.addAnimation(paniml);
group.addAnimation(panim2);
group.setLoopCount(3);
group.start();

lbll.show();
lbl2.show();

return app.exec();

. 22.1 ,
, setEasingCurve ( )
. ,
QEasingCurve .

22.1.

Linear OutExpo
InQuad InOutExpo

\
344 IV.

22.1 ()

OutQuad

Y/ OutlnExpo

InOutQuad InCirc
J
OutlnQuad
/ OutCirc

InCubic j InOutCirc
f
OutCubic
r OutlnCirc
,

InOutCubic
f InElastic j
OutInCubic
r7 OutElastic
p,

InQuart

\J InOutElastic
x
22. 345

22.1 ()

OutQuart OutlnElastic

InOutQuart
InBack j
OutlnQuart
1 OutBack

InQuint
J InOutBack
f
OutQuint
OutlnBack

InOutQuint
f InBounce
J
OutInQuint
7 OutBounce
r
InSine InOutBounce
/
346 IV.


22.1 ()

OutSine OutlnBounce
/
InOutSine
/ InCurve
/
OutlnSine _, OutCurve
/
InExpo j SineCurve
A
CosineCurve
%

(States) .
,
.
.
, ,
.
, , . .,
, - , .
.
(Transitions).
.
, : off On (

22.6). Off . Push
,
. 22.6.
22. 347

. 22.6.

22.6 ,
(wgt), setFixedSize ()
. ( pibioff pibion)
( phbx).
,
.
( QStateMachine),
. , QState, off
( pstateoff). assignProperty ()
. off
Off , a On . setinitiaistate ( ) ,
pstateoff, .
On assignProperty ,
, .
addTransitionO ,
, , .
off On
,
Push. On, .
addTransction ( ) QSignalTransition,
.
( paniml panim2) On off
addAnimation() ( ptransl ptrans2).
start().

22.6. main.cpp.

#include <QtWidgets>

int main(int argc, char** argv)


{
QApplication app(argc, argv);
QWidget wgt;
wgt.setFixedSize(300, 50);
wgt.show();
348 IV.

QLabel* plblOff = new QLabel("Off");


QLabel* plblOn = new QLabel("On");

QHBoxLayout* phbx = new QHBoxLayout;


phbx->addwidget(plblOn);
phbx->addStretch(1);
phbx->addwidget(plblOff);
wgt.setLayout(phbx);

QPushButton* pcmd = new QPushButton("Push", &wgt);


pcmd->setAutoFillBackground(true);
pcmd->show();

int nButtonWidth = wgt.widthO / 2;

QStateMachine* psm = new QStateMachine;

QState* pStateOff = new QState(psm);


QRect recti(0, 0, nButtonWidth, wgt.height());
pStateOff->assignProperty(pcmd, "geometry", recti);
pStateOff->assignProperty(plblOff, "visible", true);
pStateOff->assignProperty(plblOn, "visible", false);
psm->setInitialState(pStateOff);

QState* pStateOn = new QState(psm);


QRect rect2(nButtonWidth, 0, nButtonWidth, wgt.height());
pStateOn->assignProperty(pcmd, "geometry", rect2);
pStateOn->assignProperty(plblOff, "visible", false);
pStateOn->assignProperty(plblOn, "visible", true);

QSignalTransition* ptransl =
pStateOff->addTransition(pcmd, SIGNAL(clicked()), pStateOn);

QSignalTransition* ptrans2 =
pStateOn->addTransit ion(pcmd, SIGNAL(clicked()), pStateOff);

QPropertyAnimation* paniml =
new QPropertyAnimation(pcmd, "geometry");
ptransl->addAnimation(paniml );

QPropertyAnimation* panim2 =
new QPropertyAnimation(pcmd, "geometry");
ptrans2->addAnimation(panim2);

psm->start();

return app.exec( );
22. 349

.
,
.
QMovie,
.
setMovie ( ).
SVG
QtSvg, QSvgwidget.
Qt .

, , , . .,
. ,
,
.
.
.
, .
, ,
, ,
.
23

OpenGL

, .
.

, , ,
.

.
,
, ( ), ,
, .
.
OpenGL ,
Silicon Graphics 1992 . ,

. , ,
, . ,
OpenGL
(Anti-aliasing) .
,
.
OpenGL , ,
OpenGL- ,
(rendering
context) . OpenGL Qt
,
OpenGL- .
OpenGL Qt- QtOpenGL.
Arthur, QPainter (. 18)
OpenGL.
OpenGL .
OpenGL.

OpenGL
OpenGL -.
, .
23. OpenGL 351

OpenGL gl, GL_.


, . ,
gicolor3f() ,
(. 23.1). OpenGL,
, *. ,
: gicolor* ( ).
, , ,
gicolor.

glColor3f(...)


-
OpenGL,
. 23.1. OpenGL

. 23.1 OpenGL , .

23.1. OpenGL

OpenGL C++

GLbyte Char

S GLshort Short

i GLint Int

f GLfloat float

d GLdouble double

ub GLubyte unsigned byte

us GLushort usnigned short

ui GLuint unsigned int

GL_ GLenum Enum

v , .
, giCoior3fv()
:
GLfloat [] = { 1.Of, O.Of, O.Of}
glColor3fv(a);
352 IV.

Qt OpenGL
Qt OpenGL QtOpenGL,
:
QGL OpenGL;
QGLWidget Qwidget.
OpenGL . QGLWidget
QPainter (. 18);
QGLFormat OpenGL.
Qwidget.
QGLWidget : : format ( ) ;

QGLContex OpenGL ( ).
QGLWidget .
QGLWidget:: context ( ) ;
QGLColormap
;
QGLPixelBuffer OpenGL (pbuffer).

OpenGL-
OpenGL, QGLWidget,
OpenGL. QGLWidget
, , : initializeGLO,
resizeGL( ) paintGL ( ) . QGLWidget virtual protected.
initializeGL ( ) .
, OpenGL. , ,
QGLWidget, OpenGL.
resizeGL(int width, int height)
resizeEvent () .
, , QGLWidget.
.
paintGL
paintEvent ( ) .
,
. , ,
resizeGL .
( 23.1-23.7),

(. 23.2).

. 23.2.
23. OpenGL 353

23.1 QT (. 3),
opengl. ,
QtOpenGL.

23.1. OGLQuad.pro

TEMPLATE =
QT += opengl widgets
HEADERS = OGLQuad.h
SOURCES = OGLQuad.cpp \
main.cpp
TARGET = ../OGLQuad

, 23.2, OGLQuad,
QGLWidget.

23.2. main.cpp
#include <QApplication>
(include "OGLQuad.h"

int main(int argc, char** argv)


{
QApplication app(argc, argv);
OGLQuad oglQuad;

oglQuad.resize(200, 200);
oglQuad.show( );

return app.exec();
}

23.3 OGLQuad , QGLWidget,


: initializeGL(), resizeGL() paintGL().

23.3. OGLQuad.h
((pragma once

((include <QGLWidget>

// ====================================================
class OGLQuad : public QGLWidget {
protected:
virtual void initializeGL( );
virtual void resizeGL (int nWidth, int nHeight);
virtual void paintGL ( );

public:
OGLQuad(QWidget* pwgt = 0);
);
354 IV.

, 23.4, ,
pwgt .

23.4. OGLQuad.cpp. OGLQuad

OGLQuad::OGLQuad(QWidget* pwgt/*= 0*/) : QGLWidget(pwgt)


{
)

23.5 qgiciearcoior ( )
. Qt QCoior OpenGL,
.

OpenGL glClearColor().
qglClearColor()
QCoior.

23.5. OGLQuad.cpp. initializeGL ()

/*virtual*/void OGLQuad::initializeGL()
{
qglClearColor(Qt::black);
}

23.6 giMatrixMode ( )
. , .
giLoadidentity ( ) .
OpenGL , .
(modelview matrix)
, (projection matrix)
.
, .
resizeGLO , (viewport).
glviewPort ( ) -
( ).
.
glOrtho ( ) .
, ,
.

23.6. OGLQuad.cpp. resizeGLO

/*virtual*/void OGLQuad::resizeGL(int nWidth, int nHeight)


{
giMatrixMode(GL_PROJECTION);
giLoadidentity();
glViewport(0, 0, (GLint)nWidth, (GLint)nHeight);
glOrtho(0, 100, 100, 0, -1, 1);
)
23. OpenGL 355

giciearo
(GL_COLOR_BUFFER_BIT) (GL_DEPTH_BUFFER_BIT).
.
, qgicolor ( ) .
OpenGL . ,
, .
giBegin( ) .
GL QUADS ,
( 23.7). gicoior* ( ) ,
givertex* ( ) ,
. giBegin ( ) giEnd().
, , OpenGL
,
. glShadeModel ( ) .
GL FLAT , GL_SMOOTH
.

23.7. OGLQuad.cpp. paintGLO

/*virtual*/void OGLQuad::paintGLO
{
glClear(GL_COLOR_BUFFER_BIT I GL_DEPTH_BUFFER_BIT);

giBegin(GL_QUADS);
glColor3f(l, 0, 0);
glVertex2f(0, 100);

glColor3f(0, 1, 0);
glVertex2f(100, 100);

glColor3f(0, 0, 1);
glVertex2f(100, 0);

glColor3f(l, 1, 1);
glVertex2f(0, 0);
giEnd();
}


FTP-
- ftp://ftp.bhv.ru/9785977533461.zip
www.bhv.ru (. 4 ).

OpenGL-

QGLWidget Qwidget, ,
.
356 IV.

show ( ) showFullScreen ( ) .
.
, ,
, show ( ) showFullScreen < ).
OpenGL-
.

OpenGL
OpenGL
, , ,
. .
( 23.8-23.14) ,
(. 23.3).

. 23.3. ,

23.8 oglDraw OGLDraw.

23.8. main.cpp

#include <QApplication>
iinclude "OGLDraw.h"

int main(int argc, char** argv)


{
QApplication app(argc, argv);
OGLDraw oglDraw;

oglDraw.resize(400, 200);
oglDraw.show();

return app.exec();
23. OpenGL 357

OGLDraw QGLWidget
: initializeGLO, resizeGLO paintGLO ( 23.9).
draw(), , .
.

23.9. OGLDraw.h

#pragma once

#include <QGLWidget>

/ / ====================================================
class OGLDraw : public QGLWidget {
protected:
virtual void initializeGL( );
virtual void resizeGL (int nWidth, int nHeight);
virtual void paintGL ( );

public:
OGLDraw(QWidget* pwgt = 0);

void draw(int xOffset, int yOffset, GLenum type);


};

23.10 OGLDraw,
, - QGLWidget.

23.10. OGLDraw.cpp. OGLDraw

OGLDraw::OGLDraw(QWidget* pwgt/*= 0*/) : QGLWidget(pwgt)


{
}

23.1 1 initializeGLO
.

23.11. OGLDraw.cpp. initializeGLO

/*virtual*/void OGLDraw::initializeGL()
{
qglClearColor(Qt::white);
}

23.12 resizeGL() 23.6.

23.12. OGLDraw.cpp. resizeGLO

/*virtual*/void OGLDraw::resizeGL(int nWidth, int nHeight)


{
glMatrixMode(GL_PROJECTION);
358 IV.

glLoadldentity();
glViewport(0, 0, (GLint)nWidth, (GLint)nHeight);
glOrtho(0, 400, 200, 0, -1, 1);

23.13 paintGLO,
draw() (. 23.14).
, .
, , :
GL POINTS , ;
GL LINES , ,
, ;
GL_LINE_STRI , ,
. ,
;
GL LINE LOOP ,
;
GL TRIANGLE STRIP . ,
, ;
GL_POLYGON ;
GL QUADS
;
GL_TRIANGLES .

23.13. OGLDraw.cpp. paintGLO

/*virtual*/void OGLDraw::paintGLO
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

draw(0, 0, GL_POINTS);
draw(100, 0, GL_LINES);
draw(200, 0, GL_LINE_STRIP);
draw(300, 0, GL_LINE_LOOP);

draw(0, 100, GL_TRIANGLE_STRIP);


draw(100, 100, GL_POLYGON);
draw(200, 100, GL_QUADS);
draw(300, 100, GL_TRIANGLES);

23.14. OGLDraw.cpp. draw

void OGLDraw::draw(int xOffset, int yOffset, GLenum type)


{
int n = 8;
23. OpenGL 359

glPointSize(2);
glBegin(type);
glColor3f(0, 0, 0);
for (int i = 0; i < n; ++i) {
float fAngle =2 * 3.14 * i / n;
int x = (int)(50 + cos(fAngle) * 40 + xOffset);
int = (int)(50 + sin(fAngle) * 40 + yOffset);
glVertex2f(x, y);

glEnd();
)

23.14 draw(),
type , .
glPointSize () .
2. glColor* ( ) .
glvertex* ( ) .


( 23.15-23.23)
,
, X Y
(. 23.4).
( 23.15) OpenGL-
OGLPyramid.

. 23.4.

23.15. main.cpp
(include <QApplication>
((include "OGLPyramid.h"

int main(int argc, char** argv)


{
QApplication app(argc, argv);
OGLPyramid oglPyramid;

oglPyramid.resize(200, 200);
oglPyramid.show( );

return app.exec();
360 IV.

OGLPyramid ( 23. 1 6) m nPyramid,


.

,
, .
,
QPicture.
.
m xRotate, m yRotate X Y.
m_ptPosition .
, QGLWidget,
mousePressEvent() mouseMoveEvent() .
createPyramid() .

23.16. OGLPyramid.h

#pragma once
#include <QGLWidget>

// ==================================
class OGLPyramid : public QGLWidget {
private:
GLuint m_nPyramid;
GLfloat m_xRotate;
GLfloat m_yRotate;
QPoint m_ptPosition;

protected:
virtual void initializeGL ( );
virtual void resizeGL (int nWidth, int nHeight);
virtual void paintGL ( );
virtual void mousePressEvent(QMouseEvent* pe );
virtual void mouseMoveEvent (QMouseEvent* pe );
GLuint createPyramid (GLfloat fSize = l.Of );

public:
OGLPyramid(QWidget* pwgt = 0);
};

OGLPyramid ( 23.17)
-
QGLWidget.

23.17. OGLPyramid.cpp. OGLPyramid

OGLPyramid::OGLPyramid(QWidget* pwgt/*= 0*/) : QGLWidget(pwgt)


, m_xRotate(0)
, m_yRotate(0)
{
23. OpenGL 361

qgiciearcolor ( )
( 23. 1 8). glEnableO
.
, , gishadeMode ( ) GL FLAT,
.
createPyramidt) (. 23.23)
, m nPyramid. ,
, .

23.18. OGLPyramid.cpp. inltializeGLO

/*virtual*/void OGLPyramid::initialized,()
{
qglClearColor(Qt::black);
glEnable(GL_DEPTH_TEST);
gishadeMode1(GL_FLAT);
m_nPyramid = createPyramid(1.2f);
}

23.19 giviewPorto
. glMatrixMode ( ) .
giLoadidentity ( )
. giFrustum .
, , , , .

Z .

23.19. OGLPyramid.cpp. resized, ()

/*virtual*/void OGLPyramid::resized,(int nWidth, int nHeight)


{
glViewport(0, 0, (GLint)nWidth, (GLint)nHeight);
glMatrixMode(GL_PROJECTION);
giLoadidentity();
glFrustum(-1.0, 1.0, -1.0, 1.0, 1.0, 10.0);
}


, ( 23.20).
giLoadidentity .
glTranslate ( ) Z 3 .
giRotate ( ) X Y ,
m xRotate m yRotate. glCallListo
.

23.20. OGLPyramid.cpp. paintdO

/*virtual*/void OGLPyramid::paintGL()
{
giciear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
362 IV.

glMatrixMode(GL_MODELVIEW);
glLoadldentity();
glTranslatef(0.0, 0.0, 3.0);

glRotatef(m_xRotate, 1.0, 0.0, 0.0);


glRotatef(m_yRotate, 0.0, 1.0, 0.0);

glCallList(m_nPyramid);
)

m ptPosition
( 23.21).

23.21. OGLPyramid.cpp. mousePressEvent()


/*virtual*/void OGLPyramid::mousePressEvent(QMouseEvent* pe)
{
m_ptPosition = pe->pos();
}

( 23.22)
X . updateGL ( ) ,
. m ptPosition
.

23.22. OGLPyramid.cpp. mouseMoveEventO

/*virtual*/void OGLPyramid::mouseMoveEvent(QMouseEvent* pe)


{
m_xRotate += 180 * (GLfloat)(pe->y() m_ptPosition.y()) / height();
m_yRotate += 180 * (GLfloat)(pe->x() m_ptPosition.x()) / width();
updateGL();

m_ptPosition = pe->pos();
}

createPyramid ( )
( 23.23). glGenListsO
.
glNewList . , GL COMPILE, ,
. , glNewList giEndListo,
. GL TRIANGLE FAN
, .
. , ,
. GL QUADS
.

23.23. OGLPyramid.cpp. createPyramid()

GLuint OGLPyramid::createPyramid(GLfloat fSize/*=l.Of*/)


{
GLuint n = glGenLists(1);
23. OpenGL 363

glNewList(n, GL_COMPILE);
glBegin(GL_TRIANGLE_FAN);
qglColor(Qt::green);
glVertex3f(0.0, fSize, 0.0);
glVertex3f(-fSize, -fSize, fSize);
glVertex3f(fSize, -fSize, fSize);
qglColor(Qt::yellow);
glVertex3f(fSize, -fSize, -fSize);
qglColor(Qt::blue);
glVertex3f(-fSize, -fSize, -fSize);
qglColor(Qt::white);
glVertex3f(-fSize, -fSize, fSize);
glEnd();

glBegin(GL_QUADS);
qglColor(Qt::red);
glVertex3f(-fSize, -fSize, fSize);
glVertex3f(fSize, -fSize, fSize);
glVertex3f(fSize, -fSize, -fSize);
glVertex3f(-fSize, -fSize, -fSize);
glEnd();
glEndList();

return n;
)

OpenGL API.
, 22 . Qt
OpenGL. Qt- OpenGL
QGLWidget : initializeGLO, resizeGLO
paintGLf).
OpenGL .
OpenGL . ,
.
,
show ( ) showFullScreen().
24

,
; , ,
.
. .


. ,
: ,
,
. . Qt ,
.

QPrinter
QPrinter . ,
QPaintDevice, .
QPainter,
. QPrinter, ,
, Qt Print Support,
pro- :
QT += printsupport

QPrinter , ,
QPaintDevice. , , ,
. . Qt ,
. QPrint Dialog
(. 32). :
setOrientation ( ) ,
: QPrinter: : Portrait QPrinter: : Landscape
;
setNumCopies ( ) ;
setFromTo ( ) ;
setColorMode ( ) - .
QPrinter: : Color, -
QPrinter: Grayscale;
24. 365

setPageSize () .
, . 24.1.

24.1. Pagesize QPr inter


() ()
()
841x1189 1030x1456 32x45
1 594x841 1 728x1030 5 163x229
2 420x594 2 515x728 CommlOE 105x241
297x420 364x515 DLE 110x220
4 210x297 4 257x364 Executive 191x254
5 148x210 5 182x257 Folio 210x330
105x148 128x182 Ledger 432x279
7 74x105 7 91x128 Legal 216x356
8 52x74 8 64x91 Letter 216x279
9 37x52 9 45x64 Tabloid 279x432

.
setOutputFileName ( ) . ,
,
.
setDocName ( ) , , ,
.
, ,
PDF (Portable Document Format,
), , ,

setOutputFormat () QPrinter::PdfFormat.
QPrinter setFontEmdeddingEnabled ( )
- ,
. ,
,
.
,
abort ( ) , ,
.
( 24. 1 -24.7)
, . 24. 1.
Print ()

.

. 24.1.
366 IV.

24.1 QT
printsupport. ,
Qt Printsupport.

24.1. Printer.pro

TEMPLATE =
QT += widgets printsupport
HEADERS = Printer,h
SOURCES = Printer.cpp \
main.cpp
TARGET = ../Printer

, 24.2, (
pprinter Printer, 24.3-24.7) (
pond). clicked() slotPrint()
.

24.2. main.cpp

iinclude <QtWidgets>
#include "Printer.h"

int main(int argc, char** argv)


{
QApplication app(argc, argv);
QWidget wgt;

Printer* pprinter = new Printer;


QPushButton* pcmd = new QPushButton("&Print");

QObject::connect(pcmd, SIGNAL(clicked()),
pprinter, SLOT(slotPrint())
);

//Layout setup
QVBoxLayout* pvbxLayout = new QVBoxLayout;
pvbxLayout->setMargin(0);
pvbxLayout->setSpacing(0);
pvbxLayout->addWidget(pprinter);
pvbxLayout->addWidget(pcmd);
wgt.setLayout(pvbxLayout);

wgt.resize(250, 320);
wgt.show();

return app.exec();
24. 367

Printer, 24.3,
QPrinter. draw .
,
. slotPrint .

24.3. Printer.h

tpragma once

#include <QWidget>

class QPrinter;
class QPaintDevice;

/ / ============================================
class Printer ; public QWidget {
Q_OBJECT

private ;
QPrinter* m_pprinter;

protected:
virtual void paintEvent(QPaintEvent* pe );
void draw (QPaintDevice* ppd);

public:
Printer(QWidget* pwgt = 0);
virtual -Printer!);

public slots:
void slotPrint();
);

24.4,
m pprinter.
, .

24.4. Printer.cpp.

/I
Printer::Printer(QWidget* pwgt/*=0*/) : QWidget(pwgt)
(
m_pprinter = new QPrinter;
)

//
/*virtual*/Printer::-Printer()
{
delete m_pprinter;
368 IV.

, 24.5,
, , this.
draw ()

24.5. Printer.cpp. paintEventO

/virtual*/ void Printer : rpaintEvent (QPaintEvent* pe)


{
draw (this) ;
}

24.6 ( dig)
(mjppr inter) .
, .
setMinMaxO , .
, 1 1 .
() ,
.
QDialog: : Accepted. QPr inter ,
m_ppr inter draw ( ) .

,
,
QAbstractPrintDialog: : toPage ( ) QAbstractPrintDialog: : fromPage ( } ,
. :
int nPages = dig. toPage () - dig. fromPage ( ) + 1;


,
QPrinter::newPage() m_pprinter draw().

24.6. Printer.cpp. slotPrint()

void Printer : : slotPrint ( )


{
QPrintDialog dig (m_pprinter, this);

dig. setMinMax (1, 1);


if (dlg.execO == QDialog: : Accepted) {
draw (m_pprinter) ;

draw ( ) , 24.7, .

. , ,
, QPainter: :viewport () .
, drawRect ( ) , drawLine ( ) ,
24. 369

drawEllipse () drawTextO , ,
. setPenO setBrushO ,
. setFont ( ) .

24.7. Printer.cpp. draw()

void Printer::draw(QPaintDevice* ppd)


{
QPainter painter(ppd);
QRect r(painter.viewport());

painter.setBrush(Qt::white);
painter.drawRect(r);
painter.drawLine(0, 0, r.width(), r.heightO);
painter,drawLine(r.width(), 0, 0, r.heightO);

painter.setBrush(Qt::NoBrush);
painter.setPen(QPen(Qt::red, 3, Qt::DashLine));
painter.drawEllipse(r);

painter.setPen(Qt::blue);
painter.setFont(QFont("Times", 20, QFont::Normal));
painter.drawText(r, Qt::AlignCenter, "Printer Test");
}

, QPrinter QPaintDevice,
, .
QPrinter
, .
PDF.
25


;
.

. ,
, Qt
, .
.


, ,
.
QLineEdit ( 25.1),
(validator)
setValidator().

25.1. HexLineEdit

class HexLineEdit : public QLineEdit {


public:
HexLineEdit(QWidget* pwgt = 0) : QLineEdit(pwgt )
{
QRegExp rxp("[0-9A-Fa-f]+");
setValidator(new QRegExpValidator(rxp, this));
}
};

, 25.1, .

,
:
,
. : paintEvent(), resizeEvent(), mousePressEvent(),
mouseReleaseEvent ( ) .;
, , , ,
, private,
protected;
25. 371

, ;
, ;
sizeHintO sizePolicyO
.


sizePolicyO, setSizePolicy ()
.
. (. ),
,
. ,
, sizeHint () sizePolicyO.
sizeHint () QSize, ,
. , , .
25.2 , .
sizeHintO :
pcmdl->sizeHint () (75, 23), a pcmd2->sizeHint ()
(145, 23).

25.2. sizeHintO

QString str = "Button";


QPushButton* pcmdl = new QPushButton (str) ;
QSize size = pcmdl->sizeHint () ; // size = (75, 23)

str = "This is very long button label";


QPushButton* pcmd2 = new QPushButton (str) ;
size = pcmd2-> sizeHint ( ) ; // size = (145, 23)

QWidget: : sizePolicyO QSizePolicy,


, ,
sizeHint () .
QSizePolicy ( ),
. 25.1.

25.1. SizeType QSizePolicy


Fixed ,

sizeHint ( ) , ,
Minimum ,
sizeHint()
Maximum ,
sizeHint()
Preferred ,
sizeHint ( ) , ,

MinimumExpanding ,
sizeHintO.

372 IV.

25. 1 ()

Expanding ,
sizeHintO,
. , ,
,

Ignored , sizeHintO, .

, , QScrollview.
. ,
, sizeHintO. ,
sizeHintO, .
QScrollview, .

setSizePolicy (), Expanding

:
setSizePolicy(QSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);

( 25.3-25.8) ,
(. 25.1).
. ,
, .

. 25.1.

main ()
pew,
phsb ( 25.3).
valueChanged(int ) connect ( )
slotSetProgress(int ) ,
.

25.3. main.cpp

#include <QtWidgets>
#include "CustomWidget.h"

int main(int arge, char** argv)


{
QApplication app(argc, argv);
QWidget wgt;
25. 373

CustomWidget* pew = new CustomWidget;


QScrollBar* phsb = new QScrollBar(Qt::Horizontal);

phsb->setRange(0, 100);

QObject::connect(phsb, SIGNAL(valueChanged(int)),
pew, SLOT(slotSetProgress(int))
);

//Layout setup
QVBoxLayout* pvbxLayout = new QVBoxLayout;
pvbxLayout->addWidget(pew);
pvbxLayout->addWidget(phsb);
wgt.setLayout(pvbxLayout );

wgt.show();

return app.exec();
}

25.4 CustomWidget
m nProgress, .
paintEvent( ) sizeHint().
. progressChanged(int),
.
slotSetProgress() .

25.4. CustomWidget.h

tpragma once

#include <QFrame>

// =======================================
class CustomWidget : public QFrame {
Q_OBJECT
protected:
int m_nProgress;

virtual void paintEvent(QPaintEvent*);

public:
CustomWidget(QWidget* pwgt = 0);

virtual QSize sizeHint() const;

signals:
void progressChanged(int);
374 IV.

public slots:
void slotSetProgress (int n) ;
};

25.5 . setLinewidtho setFrameStyle ( )


. QSizePolicy: :Minimum,
setsizePolicy () , ,
, sizeHint ( ) .
QSizePolicy: : Fixed , ,
sizeHint ( ) .

25.5. CustomWidget.cpp. CustomWidget

CustomWidget : : CustomWidget (QWidget* pwgt/*= 0*/) : QFrame(pwgt)


, m_nProgress (0)
{
setLineWidth (3) ;
setFrameStyle (Box I Sunken);

setsizePolicy (QSizePolicy : :Minimum, QSizePolicy: : Fixed) ;

paintEvento ( 25.6).
painter . fillRecto
.
( f).
.
str
, drawText ( )
( AlignCenter). .painter QFrame: :drawFrame ( ) ,
QFrame .

25.6. CustomWidget.cpp. paintEvent( )

/virtual*/ void CustomWidget: :paintEvent (QPaintEvent*)


{
QPainter painter (this) ;
QLinearGradient gradient (0, 0, width (), height)));
float f = m_nProgress / 100. Of;

gradient . setColorAt (0, Qt: :black) ;


gradient . setColorAt (f, Qt: : green) ;

painter . fillRect (rect ( ) , Qt : :black) ;


painter . setBrush (gradient) ;
painter. drawRect (0, 0, (int) (width ( ) * f ) , height ());

painter . setPen (QPen (Qt : : green) ) ;


QString str = QString ( ) . setNum(m_nProgress) + "%";
painter. drawText (rect () , Qt ::AlignCenter, str);

drawFrame (.painter) ;
25. 375

25.7 slotSetProgress ()
( nProgress) ,
: 0 100. repaint()
progressChanged(int)
.

25.7. CustomWidgetcpp. - slotSetProgress ()

void CustomWidget::slotSetProgress(int n)
{
m_nProgress = n > 100 ? 100 : n < 0 ? 0 : n;
repaint();
emit progressChanged(m_nProgress);
}

25.8 sizeHintO ,
.

25.8. CustomWidgetcpp. sizeHintO

/virtual*/ QSize CustomWidget::sizeHint() const


{
return QSize(200, 30);
}

QWidget ,
.
. ,
, .
, QWidget, .
QSizePolicy,
, /,
. sizeHint ()
, ,
QSizePolicy.
26

, .


Qt (look & feel). ,
Qt- ,
. ,
-
, , .
Qt ,
, ,
, .
,
.
, ,

.
, . ,
, . ,
, ,
. , , , ,
, ,
, ,
.
, , - , , ,
, ,
. ,
, ,
, .
? ? ? ,
, .
...
.
, ,
.
, -
,
, , , .
26. 377


.
: , , , . ,
, , , .
Qt , ,
. ,
. Qt
, .
, ,
,
. ,
Qt.
,
, , , ,
, .
,
.
, CSS-, Qt-.
Qt ,
QObject
QStyle
, , . . Qt
QStyle

,
. [ QProxyStyle
. 26. 1 . QCommonStyle
QStyle .

QStyle
1QMacStyle -1
|
QGtkStyle
:
,
_l


-reverse. QFusionStyle

| QAndroidStyle J
QWindowsStyle |

[ QWindowsXPStyle ]

. 26.1.


.
. QStyle
QCommonStyle,
, .
, QStyle.
378 IV.

QCommonStyle ,
Qt.


Qt- ,
. ,
Windows Qt (. 26.1): QWindowsStyle
QFusionStyle. ,
QWindowsXPStyle, QWindowsVistaStyle, QWindowsMobileStyle, QGtkStyle, QAndroidStyle,
QWindowsCEStyle QMacStyle, .
, Qt- -style,
. ,
set Style ( ) :
QApplication: : setStyle ("QFusionStyle") ;

QApplication: : setStyle (QStyleFactory : : create ("QFusionStyle") ) ;

QApplication: : setStyle () ,
QStyleFactory: : create ( )
. QObject,
,
QApplication. setStyle ( ) ,
delete .
setStyle ,
26.1, .
Qt ,
. , , ,
, , (. 26.2).

. 26.2.

main () 26.1 wgt


. foreach,
QStyleFactory: :keys(). styledwidget ( )
, -
26. 379

. ( pgr),
className( ) , ,
QObject. (pgr)
(pvbxLayout)
. , findChildren<T>()
pgr, foreach
setstyle(), .

26.1. main.cpp

#include <QtWidgets>

//
QWidget* styledwidget(QStyle* pstyle)

QGroupBox* pgr = new QGroupBox(pstyle->metaObject()->className());


QScrollBar* psbr new QScrollBar(Qt::Horizontal);
QCheckBox* pchk new QCheckBox("sCheck Box");
QSlider* psld new QSlider(Qt: horizontal);
QRadioButton* prad new QRadioButton("SRadio Button");
QPushButton* pcmd new QPushButton("&Push Button");
//Layout setup
QVBoxLayout* pvbxLayout = new QVBoxLayout;
pvbxLayout->addwidget(psbr);
pvbxLayout->addwidget(pchk);
pvbxLayout->addwidget(psld)
pvbxLayout->addWidget(prad)
pvbxLayout->addWidget(pcmd);
pgr->setLayout(pvbxLayout);

QList<QWidget*> pwgtList = pgr->findChildren<QWidget*>();


foreach(QWidget* pwgt, pwgtList) {
pwgt->setStyle(pstyle);

return pgr;
}

//
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QWidget wgt;

//Layout setup
QHBoxLayout* phbxLayout = new QHBoxLayout;
foreach (QString str, QStyleFactory::keys()) {
phbxLayout->addWidget(styledwidget(QStyleFactory::create(str)));
}
380 IV.

wgt.setLayout(phbxLayout);

wgt.show();

return app.exec();
}

( 26.2-26.4)
.
(. 26.3).

. 26.3.

26.2 MyApplication.
26.3, 26.4.

26.2. main.cpp

#include <QApplication>
#include "MyApplication.h"

int main (int argc, char** argv)


{
QApplication app(argc, argv);
MyApplication myApplication;

myApplication.show();

return app.exec();
}

MyApplication ( 26.3) QWidget. ,


slotChangeStyle(const QStrings),
.

26.3. MyApplication.h

#pragma once

#include <QWidget>

// ======================

class MyApplication : public QWidget {


Q OBJECT
26. 381

public:
MyApplication(QWidget* pwgt = 0);

public slots:
void slotChangeStyle(const QStrings str);
};

26.4 MyApplication
, additems ( )
, QStyleFactory::keys () .
connect () activated(const QStrings)
slotChangeStyle(const QStrings).
, .
QStyleFactory::create () , .
setStyleO,
.

26.4. MyApplication.cpp

#include <QtGui>
iinclude "MyApplication.h"

//
MyApplication::MyApplication(QWidget* pwgt/*= 0*/) : QWidget(pwgt)
{
QComboBox* pcbo = new QComboBox;
QSpinBox* pspb = new QSpinBox;
QSlider* psld = new QSlider(Qt: horizontal);
QRadioButton* prad = new QRadioButton("SRadio Button");
QCheckBox* pchk = new QCheckBox("&Check Box");
QPushButton* pcmd = new QPushButton("&Push Button");

pcbo->addItems(QStyleFactory::keys());

connect(pcbo,
SIGNAL(activated(const QStrings)),
SLOT(slotChangeStyle(const QStrings))
);

//Layout setup
QVBoxLayout* pvbxLayout = new QVBoxLayout;
pvbxLayout->addWidget(pcbo);
pvbxLayout->addWidget(pspb);
pvbxLayout->addWidget(psld);
pvbxLayout->addWidget(prad);
pvbxLayout->addWidget(pchk);
pvbxLayout->addWidget(pcmd);
setLayout(pvbxLayout);
382 IV.

void MyApplication::slotChangeStyle(const QStrings str)


{
QStyle* pstyle = QStyleFactory::create(str);
QApplication::setStyle(pstyle);
)


QStyle.
QWidget: :styled. QStyle :
, , sizeHinto
. .
Qt
CSS ( ),
.
, , , ,
. QStyle, .
, ,
. ,
, .
QStyle ,
. , ,
, QStyle:
drawPrimitive ( ) ;
drawControi ( ) ;

drawComplexControi ( ) .

, , .
QStyleOption.
public, :
version () . QStyleOption
, ;
type () ;
state () , :
(enabled), (active), (pressed) . .;
direction () ,
Qt : :LeftToRight, Qt : :RightToLeft;
rect (. ) ,
;
fontMetrics () ;
palette () .
26. 383

,
QStyleOption. ,
, , QStyleOption,
, .
. :
class MyStyleOptionProgress : public QStyleOption {
enum {Type = SO_ProgressBar};
enum {Version = 1);
int nMaximum;
int nMinimum;
int nProgress;
QString str;
Qt::Alignment textAlignment;
};

, ,
.



, ,
.
drawPrimitive():
void drawPrimitive(PrimitiveElement elem,
const QStyleOption* popt,
QPainter* ppainter,
const QWidget* pwgt = 0
)

, ,
. QStyleOption,
. QPainter,
. .
, ,
.


, , ,
.
drawControl():
void drawControl(ControlElement elem,
const QStyleOption* popt,
QPainter* ppainter,
const QWidget* pwgt = 0
)
384 IV.

, ,
. drawPrimitive().


, , ,
, , . .
drawComplexControl():
void drawComplexControl(ComplexControl control,
const QStyleOptionComplex* popt,
QPainter* ppainter,
const QWidget* pwgt = 0
)

.
QStyleOption, ,
QStyleOptionComplex. QStyleOption
, , , ,

.



,
, , ,
QComboBox, .

,
, . ,
26.5-26.9, , (. 26.4).

. 26.4.

main(), 26.5, ,
QPushButton. setstyleO
CustomStyle.

26.5. main.cpp

#include <QtWidgets>
#include "CustomStyle.h"
26. 385

int main (int argc, char** argv)


{
QApplication app(argc, argv);
QWidget wgt;

QPushButton* pcmdA = new QPushButton ("Buttonl");


QPushButton* pcmdB = new QPushButton ("Button2");
QPushButton* pcmdC = new QPushButton ("Button3");

//Layout setup
QVBoxLayout* pvbxLayout = new QVBoxLayout;
pvbxLayout->addWidget(pcmdA);
pvbxLayout->addWidget(pcmdB);
pvbxLayout->addwidget(pcmdC);
wgt.setLayout(pvbxLayout );

app.setStyle(new CustomStyle);
wgt.show();

return app.exec();
}

26.6 CustomStyle QCommonStyle.


polish unpolish , QStyie.
.
,
.
drawPrimitive ( ) ,
(primitive control element).
elem , .
QStyleOption.
QPainter ( ppainter),
. pwgt ,
.

26.6. CustomStyle.h
#pragma once

#include <QtWidgets>

class QPainter;

/ / ======================================
class CustomStyle : public QCommonStyle {
public:
virtual void polish (QWidget* pwgt);
virtual void unpolish(QWidget* pwgt);
386 IV.

virtual void drawPrimitive ( PrimitiveElement elem,


const QStyleOption* popt,
QPainter* ppainter,
const QWidget* pwgt = 0
) const;
};

polish ( ) ( 26.7).
, Qt::WA_Hover
QPushButton true. ,
Qt .
.

26.7. CustomStyle.cpp. polish()

void CustomStyle: : polish (QWidget* pwgt)


{
if (qobject_cast<QPushButton*> (pwgt) ) {
pwgt->setAttribute (Qt : :WA_Hover, true) ;

,
unpolish
polish .
Qt : :WA_Hover false ( 26.8).

26.8. CustomStyle.cpp. unpolish()

void CustomStyle: : unpolish (QWidget* pwgt)


{
if (qobject_cast<QPushButton*> (pwgt) ) {
pwgt->setAttribute (Qt : :WA_Hover, false) ;

( 26.9) switch.
case, , .
.
QStyleOption , ,
. , ,
QStyleOptionButton.
,
.
bDown :
btnprs.bmp,
btn.bmp. QPainter: :drawPixmap ( ) .
bHover true, .
QPainter: :fiiiRect()
, .
26. 387

pwgt, , ,
. , ,
QStyleOption.
- pwgt, ,
, , ,
.
, , .
. default
.

26.9. CustomStyle.cpp. drawPrimitive ()

void CustomStyle::drawPrimitive( PrimitiveElement elem,


const QStyleOption* popt,
QPainter* ppainter,
const QWidget* pwgt
) const
{
switch (elem) {
case PE_PanelButtonCommand:
{
const QStyleOptionButton* pOptionButton =
qstyleoption_cast<const QStyleOptionButton*>(popt);
if (pOptionButton) {
bool bDown = (pOptionButton->state & State_Sunken)
I I (pOptionButton->state & State_On);
QPixmap pix = bDown ? QPixmap(":/images/btnprs.bmp")
: QPixmap(":/images/btn.bmp");

ppainter->drawPixmap(pOptionButton->rect, pix);

bool bHover = (pOptionButton->state & State_Enabled)


&& (pOptionButton->state & State_MouseOver);
if (bHover) {
ppainter->fillRect(pOptionButton->rect,
QColor(25, 97, 45, 83)
);
}
}
break;
}

default:
QCommonStyle::drawPrimitive(elem, popt, ppainter, pwgt);
break;
}
return;
388 IV.

QStyle

QStyle ,
. , , ,
, ,
, Qt.
, (QLabel), ,
. ,
26.10. . 26.5.

. 26.5. ,

QStylePainter.
, QPainter.
QStyleOptionPushButton, . initFromO
, : , , ,
. . .
This is a label. drawControl()
QStylePainter, .

26.10. CustomStyle.cpp

void MyLabel: ipaintEvent(QPaintEvent*)


{
QStylePainter painter(this);
QStyleOptionButton option;

option.initFrom(this);
option.text = "This is a label";

painter.drawControl(QStyle::CE_PushButton, option);
}


,
. , C++.
, C++
, , , C++
,
. ,
, C++, -
26. 389

, .
,
.
Qt . CSS (Cascading
Style Sheets, ), HTML. Qt
, ,
. Qt Designer (. 44)
CSS-,
.
, , .
, qss.
, QApplication::setstyleSheet ( ) ,
QWidget::setstyleSheet().
, -stylesheet
CSS-:

-stylesheet MyStyle.qss

,
Qt-.


CSS :
{: }
. ,
, . ,
. ,
:
QLineEdit {color: red}
, ,
, :
QLabel {
color: red;
background-color: white;
}

RGB HTML-:
QLabel {
color: rgb(255, 0, 0);
background-color: #FFFFFF;
}

background-image
. :
QLabel {
background-image: url(pic.png);
}
390 IV.

,
. ,
:
QPushButton, QLineEdit, QLabel {color: red}

,
. ,
. :
.PushButton {color: red}

(*).
,
, QLabel#MyLabel
QLabel MyLabel.
,
, :
namespace MyNameSpace {
class MyClass : public QWidget {

};
}

CSS :
MyNameSpace MyClass {
background-colode: black;
color: white;

, : COLOR = color = COLOR . .


.
CSS , C/C++,
/* */, :
/* */


.
.
. ,
QComboBox
:
QComboBox::drop-down {image: url(pic.png) }

, , :
QPushButton::menu-indicator {image: url (downarrow.png) }

. 26.1 .
26. 391

26.1.




. , ,
: : down-arrow

: : down-button .
d
: : drop-down

,
: : indicator
0
:: item , 0
,
:: menu-indicator
j

: : title Title
:: up-arrow .

:: up-but ton .
0
, . :
QPushButton: : menu-indicator : hover { image: url (hovereddownarrow.png) }

subcontrol-position. ,
, :
QPushButton: : menu-indicator { subconrol-position: right center}


, (. 26.2).
, ()
. , ,
:
QPushButton: hover {color: red}

26.2.


: checked
: closed
: disabled
: enabled
392 IV.

26.2 ()


: focus
: hover
: indeterminate
:off ( ,
/ )
:on ( ,
/ )
:open
:pressed
: unchecked

. ,
, ,
:
QCheckBox:hover:checked {color: white}

, ,
, :
QCheckBox:hover, QCheckBox:checked {color: white}
, :
QCheckBox:!hover {color: white}

, . ,
, , (. . 26.4).
26.1 1.
, 80 .
,
, .
border-image border-width
,
, .

26.11. simple.qss

/* Simple Style */
QPushButton {
min-width: 8Opx;
}

QPushButton {
border-image: url(:/style/btn.bmp) 5px;
26. 393

border-width: 5;
}

QPushButton:hover {
border-image: url(:/style/btnhvd.bmp) 5px;
border-width: 5px;
}

QPushButton:pressed {
border-image: url(:/style/btnprs.bmp) 5px;
border-width: 5px;
}

26.12, 26.5, ,
.
, ,
strCSS QApplicaiton::setStyleSheet ( ) .

,
, :
qApp->setStyleSheet("QPushButton::hover {background-color: blue}");
,
, (. 26.6).

26.12. main.cpp

#include <QtWidgets>

int main (int arge, char** argv)


{
QApplication app(argc, argv);
QWidget wgt;

QPushButton* pcmdA = new QPushButton ("Buttonl");


QPushButton* pcmdB = new QPushButton ("Button2");
QPushButton* pcmdC = new QPushButton ("Button3");

//Layout setup
QVBoxLayout* pvbxLayout = new QVBoxLayout;
394 IV.

pvbxLayout->addWidget(pcmdA);
pvbxLayout->addWidget(pcmdB);
pvbxLayout->addWidget(pcmdC);
wgt.setLayout(pvbxLayout);

QFile file(":/style/simple.qss");
file.open(QFile::Readonly);
QString strCSS = QLatinlString(file.readAll());

qApp->setStyleSheet(strCSS);
wgt.show();

return app.exec();
}

26.13 ,
16 ( min-width). , background,
. (xi, yi) (2, 2) ,
1 0.4. ,
- . ,
( color). ,
( border) (
border-radius).

26.13.

QPushButton {
min-width: 1;
background: qlineargradient(xl:0, yl:l, x2:0, y2:0,
stop:l rgb{133,133,135),
stop:0.4 rgb(31, 31, 33)
color: white;
border: lpx solid white;
border-radius:5px;

26.14 , ,
. ,
26.13, .
.

26.14.

QPushButton:hover {
background: qlineargradient(xl:0, yl:l, x2:0, y2:0,
stop:l rgb(133,133,135),
stop:0.4 rgb(31, 31, 33),
stop:0.2 rgb(0, 0, 150) );
}
26. 395

( 26.15),
. ,
.

26.15.

QPushButton:pressed {
background: qlineargradient (xl:0, yl:0, x2:l, y2:0,
stop:0 rgba(l, 1, 5, 80),
stop:0.6 rgba(18, 18, 212, 80),
stop:0.5 rgba (142, 142, 245,80)
border: lpx solid rgb(18, 18, 212);

(toggle),
, , ,
-
( 26.16).

26.16.

QPushButton:checked {
background: qlineargradient (xl:0, yl:0, x2:0, y2:l,
stop:l rgb(133,133, 135),
stop:0.4 rgb(31, 31, 33) );
border: lpx solid rgb(18, 18, 212);
}


,
( 26.17).

26.17.

QPushButton:checked:hover {
background: qlineargradient (xl:0, yl:l, x2:0, y2:0,
stop:l rgb(31, 31, 33),
stop:0.4 rgb(133,133, 135),
stop:0.1 rgb(0, 0, 150) );
}

,
border-radius. ,
.

? border- image.
, .

, .
border- image 9 (. 26.7).
396 IV.

,
.
border-image :
top ;
right ;
bottom ;
left .
. 26.7
:
border-image: url(button.png) 9, 2, 5, 2

left right
e

, , top, right,
bottom left . :
border-image: url(button.png) 5

Qt
(look & feel) .
, . ,
,
QApplication::setStyle().
.
, . ,
QStyle, .
, .
,
.
QStyleOption.
Qt ,
CSS. CSS- C++ ,
,
. .
, ,
.
27

, .

-, ,
,
, Web-,
.
, , , , .
, ,
. ,
.

. .
?
, ,
50- .

, -
.
: multum , medium
. , ,
.
, , , , ,
, Web- . . , ,
. QtMultimedia,
Qt .

, 30 % .

.
, .
, ,
.
398 IV.

, , ,
.
,
QApplication: :beep ( ) . , ,
.
, , ,
, ,
, , - .

WAV-:
QSound
QSound
WAV, ,
, , , , ,
, WAV,
QMediaPlayer, .
QSound play ,
.
, ,
. :

QSound::play(" : /yesterday .wav" ) ;

,
, QSound.
setLoops ( ) ,
. -1 .
play ( ) :

.
QSound sound ( " : /yesterday wav" ) ;
sound. setLoops (3) ; //3
sound.play ( ) ;

,
QSound: : loopsRemaining ( ) , .
, QSound: : stop .

:
sound. stop ( ) ;

, , , QSound
play ( ) .
,
, QSound: :isFinished(), true
, , false,
. , isFinished ( ) false.
27. 399


: QMediaPlayer
QMediaPlayer ( ) ,
. ,
, , -.
, .
:
QMediaPlayer* pPlayer = new QMediaPlayer;
pPlayer->setMedia(QUrl::fromLocalFile(":/yesterday.mp3"));
pPlayer->play();

QMediaPlayer,
setMediaO - play ( ) ,
. .
, setMedia ( ) QUrl,
QMediaPlayer
, ,
.
,
QUrl::fromLocalFile ( ) , url.
,
, , ,
.
.
, . 27.1,
, ,
, ,
.

. 27.1.

,
:
QT += multimedia
( 27.1) SoundPlayer,
resize ( ) , show ( ) , .

27.1. . main.cpp

#include <QApplication>
#include "SoundPlayer.h"
400 IV.

int main(int argc, char** argv)


{
QApplication app(argc, argv);
SoundPlayer soundPlayer;

soundPlayer.resize(320, 75);
soundPlayer.show();

return app.exec();
)

SoundPlayer, 27.2,
QMediaPlayer,
, . SoundPlayer
QWidget.
msecToString ( ) , private,
,
.
:
slotopen ( ) ;
slotplay ( ) ;
slotSetsliderPostion ( )

;
siotSetMediaPositionO
QMediaPlayer;
siorSetDuration() ;
slotStatusChanged() QMediaPlayer.

27.2. SoundPlayer.h

#pragma once
ftinclude <QWidget>
#include <QMediaPlayer>

class QPushButton;
class QSlider;
class QLabel;
class QVBoxLayout;

/ / ======================================
class SoundPlayer : public QWidget {
Q_OBJECT
protected:
QMediaPlayer* m_pmp;
QVBoxLayout* m_pvbxMainLayout;
27. 401

private:
QPushButton* m_pcmdPlay;
QPushButton* m_pcmdStop;
QSlider* m_psldPosition;
QLabel* m_plblCurrent;
QLabel* m_plblRemain;

QString msecsToString(qint64 n);

public:
SoundPlayer(QWidget* pwgt = 0);

private slots:
void slotOpen ( );
void slotPlay ( );
void slotSetSliderPosition(qint64 );
void slotSetMediaPosition (int );
void slotSetDuration (qint64 );
void slotStatusChanged (QMediaPlayer::State);
};

( 27.3)
. m_pcmdPlay m pcmdstop
setEnabied ( ) . ,
, .

setRange ( ) setorientaion( )
Qt::Horizontal .
, ,
, setOrientationO .
setRange () 0 100
: (
psldVolume) QMediaPlayer ( m_pmp).
-
. , ( pcmdOpen)
SoundPlayer : :slotOpen ( ) . Play ( m_pcmdPlay)
SoundPlayer::slotPlay(). Stop ( m_pcmdstop)
( ) QMediaPlayer: : stop .
( psldVolume)
QMediaPlayer::setvolume . ,
, ,
QMediaPlayer.
,
, (
m pmp), QSlider::sliderMoved()
slotSetMediaPosition(). ,
, ,
.
402 IV.

SoundPlayer slotSetPositionO,
QMediaPlayer: ipositionChanged().
!
. Qt
, ,
.
QMediaPlayer::duration!)
QMediaPlayer::setMedia() .
, QMediaPlayer::
durationchanged!). 27.3,
SoundPlayer::slotSetDuration().

QMediaPlayer::stateChanged () slotStatusChanged ( )
SoundPlayer.

SoundPlayer .

27.3. SoundPlayer. SoundPlayer.cpp


SoundPlayer::SoundPlayer(QWidget* pwgt/*=0*/) : QWidget(pwgt)
{
QPushButton* pcmdOpen = new QPushButton("&Open");
QSlider* psldVolume = new QSlider;

m_pcmdPlay = new QPushButton;


m_pcmdStop = new QPushButton;
m_psldPosition = new QSlider;
m_plblCurrent = new QLabel(msecsToString(0));
m_plblRemain = new QLabel(msecsToString(0));
m_pmp = new QMediaPlayer;

m_pcmdPlay->setEnabled(false);
m_pcmdPlay->setIcon(style()->standardIcon(QStyle::SP_MediaPlay));

m_pcmdStop->setEnabled(false);
m_pcmdStop->setIcon(style()->standardIcon(QStyle::SP_MediaStop));

m_psldPosition->setRange(0, 0);
m_psldPosition->setOrientation(Qt::Horizontal);

psldVolume->setRange(0, 100);
int nDefaultVolume = 50;
m_pmp->setVolume(nDefaultVolume);
psldVolume->setValue(nDefaultVolume);

connect(pcmdOpen, SIGNAL(clicked()), SLOT(slotOpen()));


connect(m_pcmdPlay, SIGNAL(clicked()), SLOT(slotPlay()));
connect(m_pcmdStop, SIGNAL(clicked()), m_pmp, SLOT(stop()));
27. 403

connect(psldVolume, SIGNAL(valueChanged(int)),
m_pmp, SLOT(setVolume(int))
);

connect(m_psldPosition, SIGNAL(sliderMoved(int)),
SLOT(slotSetMediaPosition(int))
);

connect(m_pmp, SIGNAL(positionChanged(qint64)),
SLOT(slotSetSliderPosition(qint64))
);
connect(m_pmp, SIGNAL(durationChanged(qint64)),
SLOT(slotSetDuration(qint64))
);
connect(m_pmp, SIGNAL(stateChanged(QMediaPlayer::State)),
SLOT(slotStatusChanged(QMediaPlayer::State))
);

//Layout setup
QHBoxLayout* phbxPlayControls = new QHBoxLayout;
phbxPlayControls->addWidget(pcmdOpen);
phbxPlayControls->addWidget(m_pcmdPlay);
phbxPlayControls->addWidget(m_pcmdStop);
phbxPlayControls->addWidget(psldVolume);

QHBoxLayout* phbxTimeControls = new QHBoxLayout;


phbxTimeControls->addWidget(m_plblCurrent);
phbxTimeControls->addWidget(m_psldPosition);
phbxTimeControls->addWidget(m_plblRemain);

m_pvbxMainLayout = new QVBoxLayout;


m_pvbxMainLayout->addLayout(phbxPlayControls);
m_pvbxMainLayout->addLayout(phbxTimeControls);

setLayout(m_pvbxMainLayout);
}

slotopen() ( 27.4) ,
, , ,
QUrl QMediaPlayer::setMedia(). ,
, Play Stop .

27.4. slotOpen(). SoundPlayer.cpp

void SoundPlayer::slotOpen()
{
QString strFile = QFileDialog::getOpenFileName(this,
"Open File"
);
404 IV.

if (!strFile.isEmpty()) {
m_pmp->setMedia(QUrl::fromLocalFile(strFile));
m_pcmdPlay->setEnabled(true);
m_pcmdStop->setEnabled(true);

slotPlayO ( 27.5) Play, ,


, QMediaPlayer::
state ( ) ( m pmp), play ( ) pause ( ) .
, :
QMediaPlayer::PlayingState,
QMediaPlayer::pause ( )
. QMediaPlayer::play()
.

27.5. slotPlay () . SoundPlayer.cpp

void SoundPlayer::slotPlay()
{
switch(m_pmp->state()) {
case QMediaPlayer::PlayingState:
m_pmp->pause();
break;
default:
m_pmp->play();
break;

slotstatusChanged ( ) ( 27.6) .
: QMediaPlayer::StoppedState ( ), QMediaPlayer::PlayingState
( ) QMediaPlayer::PausedState (
). 27.6 :
QMediaPlayer::PlayingState, ,
, .
.

27.6. slotstatusChanged(). SoundPlayer.cpp

void SoundPlayer::slotstatusChanged(QMediaPlayer::State state)


{
switch(state) {
case QMediaPlayer::PlayingState:
m_pcmdPlay->setIcon(style()->standardIcon(QStyle::SP_MediaPause));
break;
default:
m_pcmdPlay->setIcon(style()->standardIcon(QStyle::SP_MediaPlay));
break;
27. 405

slotSetMediaPosition ( ) ( 27.7) QMediaPlayer::setPosition()


, qint64.
sliderMovedo int.
qint64 int.

27.7. slotSetMediaPosition () . SoundPlayer.cpp

void SoundPlayer::slotSetMediaPosition(int n)
{
m_pmp->setPosition(n);
}

msecsToString ( ) , 27.8,
QTime,
.

27.8. msecsToString () . SoundPlayer.cpp

QString SoundPlayer: imsecsToString(qint64 n)


{
int nHours = (n / (60 * 60 * 1000));
int nMinutes = ((n % (60 * 60 * 1000)) / (60 * 1000));
int nSeconds = ((n % (60 * 1000)) / 1000);

return QTime(nHours, nMinutes, nSeconds).toString("hh:mm:ss");


)

siotSetDuration ( ) ( 27.9)
. (
m psidPosition) ,
setRange().
msecsToString (), 27.8,
( m_plblCurrent
m_plblRemain).

27.9. siotSetDuration () . SoundPlayer.cpp

void SoundPlayer::siotSetDuration(qint64 n)
{
m_psldPosition->setRange(0, n);
m_plblCurrent->setText(msecsToString(0));
m_plblRemain->setText(msecsToString(n));
)

siotSetsiiderPositionO ( 27.10)
.
setvaiue ( ) ( m psidPosition).
setText ( )
( m_pibicurrent).
406 IV.

, ,
nDuration. , ,
QMediaPlayer::duration(), .
,
( m plblRemain)
setText ().

27.10. slotSetSliderPosition(). SoundPlayer.cpp

void SoundPlayer::slotSetSliderPosition(qint64 n)
{
m_psldPosition->setValue(n);

m_plblCurrent->setText (msecsToString (n) );


int nDuration = m_psldPosition->maximum( );
m_plblRemain->setText (msecsToString (nDuration - n));
}

QMediaPlayer
, QMediaPlayer ,
, .
,
. 27.2. ,
(. . 27.1).
, .

00:13:18 00:42:08

Q I |1

If d IS pi I3CJ Lf I I facebook.com/inside.out.world

. 27.2.
27. 407

VideoPlayer SoundPlayer
(. 27.1-27.10) .
,
, .
QVideoWidget,
QtMultimediaWidget, ,
QtMultimedia, :
QT += multimedia multimediawidgets
( 27.1 1)
VideoPlayer, resize ()
show().

27.11. . main.cpp

#include <QApplication>
#include "VideoPlayer.h"

//
int main(int argc, char** argv)
{
QApplication app(argc, argv);
VideoPlayer VideoPlayer;

VideoPlayer.resize(400, 450);
VideoPlayer.show();

return app.exec();
}

27.12 VideoPlayer
SoundPlayer (. 27.1-27.10).

27.12. VideoPlayer.h

#pragma once
#include "../SoundPlayer/SoundPlayer.h"

/ / ========================================
class VideoPlayer : public SoundPlayer {
Q_OBJECT

public:
VideoPlayer(QWidget* pwgt = 0);
};


( 27.13) QVideoWidget
. 300x300 ,
( setMinimumSize ).
408 IV.

(m_pvbxMainLayout) addwidget ( ) . setVideoOutput(),


( m pmp). .

27.13. VideoPlayer. VideoPlayer.cpp

#include <QtWidgets>
#include <QVideoWidget>

#include "VideoPlayer.h"

//
VideoPlayer::VideoPlayer(QWidget* pwgt/*=0*/) : SoundPlayer(pwgt)
{

QVideoWidget* pvw = new QVideoWidget;


pvw->setMinimumSize(300, 300);

m_pvbxMainLayout->addWidget(pvw);

m_pmp->setVideoOutput(pvw);
}


WAV- QSound.
, . QSound
,
, , , WAV.
, QMediaPlayer
, .
QUrl,
,
.
:
, ,
;
;
;
.
QVideoWidget,
setVideoOutput ( ) QMediaPlayer.

, .
.

28.
29.
30.
31.
32.
33.
34. , SDI- MDI-
35. (Desktop)
28

...
,
.
, - IBM


. ,
, ,
:
, , .
,
.
. (key)
,
(key value).
, , . , ,
Windows, , ,
HKEY_LOCAL_MACHINE\Software HKEY_CURRENT_USER\Software.

Windows
.

Linux $HOME/.qt $QTDIR/etc.


Qt QSettings.
. :
QSettings settings ( "BHV" , "MyProgram") ;

,
, QCoreApplication
setOrganisationName setApplicationName ( ) . :
QCoreApplication: : setOrganizationName ( "BHV" ) ;
QCoreApplication: : setApplicationName ("MyProgram") ;

setvaiue ( ) .
, . , -
412 V.

. QVariant (. 4),
: bool, double, int, QString, QRect, Qimage . .
:
settings.setValue("/Settings/StringKey", "String Value");
settings.setValue("/Settings/IntegerKey", 213);
settings.setValue("/Settings/BooleanKey", true);

value ( ) ,
QVariant. QSettings
QVariant
. . valued
: , ,
, . :
QString str = settings.value("/Settings/StringKey", "").toString();
int n = settings.value("/Settings/IntegerKey", 0).tolnt();
bool b = settings.value("/Settings/BooleanKey", false).toBool();
remove ( )
QSettings:
settings.remove("/Settings/StringKey");

,
beginGroup ( ) . , ,
endGroup ( ) . ,
. beginGroup
endGroup ( ) :
settings.beginGroup("/Settings");
settings.beginGroup("/Colors");
int nRed = settings.value("/red");
settings.endGroup();

settings.beginGroup("/Geometry");
int nwidth = settings.value("/width") ;
settings.endGroupO ;
settings.endGroup();

, 28.1-28.8, , . 28.1.
.
: Classic
(), , , Borland (
Borland), , . Disable edit (
) / .

.
28.1 MyProgram.

28.1. main.cpp

tinclude <QApplication>
#include "MyProgram.h"
28. 413

int main(int argc, char** argv)


{
QApplication app(argc, argv);
MyProgram myProgram;

myProgram.show();

return app.exec();
}

. 28.1. ,

MyProgram, 28.2, m settings


QSettings. (m pcbo),
(m pchk), (m ptxt), (m pibi)
(m nCounter). MyProgram
(writeSettings () readSettings()).
: slotCheckedBoxClickedO slotComboBoxActivated()
,
.

28.2. MyProgram.h

#pragma once

#include <QWidget>
#include <QSettings>

class QComboBox;
class QCheckBox;
class QTextEdit;
class QLabel;

// ===============================
class MyProgram : public QWidget {
Q OBJECT
414 V.

private:
QSettings mjsettings;
QComboBox* m_pcbo;
QCheckBox* m_pchk;
QTextEdit* m_ptxt;
QLabel* m_plbl;
int m_nCounter;

public:
MyProgram(QWidget* pwgt =0);
virtual ~MyProgram();

void writeSettings();
void readSettings ();

public slots:
void slotCheckBoxClicked ( );
void slotComboBoxActivated(int);
};

28.3 m settings :
"BHVM "MyProgram.
(m_plbl), (m_ptxt),
(m_pcbo) (m_pchk). additemO
Classic Borland, .
clicked {) ( m_pchk)
slotCheckBoxClicked ( ) , activated(int)
slotComboBoxActivated(int ) . readSettings .
(. 6).

28.3. MyProgram.cpp. MyProgram

MyProgram::MyProgram(QWidget* pwgt/*=0*/)
: QWidget(pwgt)
, m_settings("BHV","MyProgram")
{
m_plbl = new QLabel;
m_ptxt = new QTextEdit;
m_pcbo = new QComboBox;
m_pchk = new QCheckBox("Disable edit");

m_pcbo->addItem("Classic");
m_pcbo->addItem("Borland");

connect(m_pchk, SIGNAL(clicked( ) ) , SLOT(slotCheckBoxClicked()));


connect(m_pcbo,
SIGNAL(activated(int)),
SLOT(slotComboBoxActivated(int))
);
28. 415

readSettings();

//Layout setup
QVBoxLayout* pvbxLayout = new QVBoxLayout;
QHBoxLayout* phbxLayout = new QHBoxLayout;
pvbxLayout->setMargin(5);
phbxLayout->setSpacing(15);
pvbxLayout->setSpacing(15);
pvbxLayout->addWidget(m_plbl);
pvbxLayout->addWidget(m_ptxt);
phbxLayout->addWidget(m_pcbo);
phbxLayout->addWidget(m_pchk);

pvbxLayout->addLayout(phbxLayout);
setLayout(pvbxLayout);

28.4 readSettings ,
beginGroup ( ) QSettings .
, .
strText /text, readEntryO .
, /text , ,
, .
nwidth nHeight, , nComboitem,
, bEdit,
, m nCounter, .
.
m_nCounter . ,
, endGroup().

28.4. MyProgram.cpp. readSettings ()

void MyProgram::readSettings()
{
m_settings.beginGroup("/Settings");

QString strText = m_settings.value("/text", "").toString();


int nwidth = m_settings.value("/width", width()).tolnt();
int nHeight = m_settings.value("/height", height()).tolnt();
int nComboitem = m_settings.value("/highlight", 0).tolnt();
bool bEdit = m_settings.value("/edit", false).toBool();

m_nCounter = m_settings.value("/counter", 1).tolnt ();

QString str = QString().setNum(m_nCounter++);


m_plbl->setText("This program has been started " + str + " times");

m_ptxt->setPlainText(strText);
416 V.

resize(nWidth, nHeight);

m_pchk->setChecked(bEdit);
slotCheckBoxClicked();

m_pcbo->setCurrentIndex(nComboItem);
slotComboBoxActivated(nComboItem);

m_settings.endGroup();
}

, 28.5, ,
, .
writeSettings().

28.5. MyProgram.cpp. -MyProgram()

/*virtual*/Program::~Program()
{
writeSettings();
}


closeEvent(),
.

writeSettings()
beginGroupO .
setvalue(), ,
(
28.6).

28.6. MyProgram.cpp. writeSettings ()

void MyProgram::writeSettings()
{
m_settings.beginGroup("/Settings");
m_settings.setvalue("/counter", m_nCounter);
m_settings.setValue("/text", m_ptxt->toPlainText());
m_settings.setvalue("/width", width());
m_settings.setvalue("/height", height());
m_settings.setvalue("/highlight", m_pcbo->currentIndex());
m_settings.setvalue("/edit", m_pchk->isChecked());
m_settings.endGroup();
}

slotCheckBoxClicked()
,
isChecked()( 28.7).
28. 417

28.7. MyProgram.cpp. slotCheckBoxClicked()

void MyProgram::slotCheckBoxClicked()
{
m_ptxt->setEnabled(!m_pchk->isChecked());
}

siotComboBoxActivated( ) , 28.8,

.
QPalette: : Active (. 13).

28.8. MyProgram.cpp. siotComboBoxActivated()

void MyProgram::siotComboBoxActivated(int n)
{
QPalette pal = m_ptxt->palette();
pal.setColor(QPalette::Active,
QPalette::Base,
n ? Qt::darkBlue : Qt::white
);
pal.setColor(QPalette::Active,
QPalette::Text,
n ? Qt::yellow : Qt::black
>;
m_ptxt->setPalette(pal);
)


. QApplication
. ( 28.9).

28.9.

class : public QApplication {


Q_OBJECT
private:
QSettings* m_pSettings;

public:
App tints argc,
char** argv,
const QStrings strOrg,
const QStrings strAppName
) : QApplication(argc, argv)
, m_pSettings(0)
{
setOrganizationName(StrOrg);
setApplicationName(strAppName);
418 V.

m_pSettings = new QSettings(strOrg, strAppName, this);


}

static App* theAppO


{
return (App*)qApp;
}

QSettings* settings()
(
return m_pSettings;
}

argc, argv
QApplication. strOrg
strAppName.
QCoreApplication::setOrganizationName ( ) QCoreApplication;:
setApplicationName ( )
( m_pSettings). theAppO ,
.
settings ( ) .
:
int main(int argc, char** argv)
{
App app(argc, argv, "MyCompany", "MyApp");

return app.exec();
)

:
QSettings pst = App;:theApp()->settings();
pst->setValue("Language", "en");


,
, .
.
, .
,
.
QApplication
QApplication::commitData ( ) QApplication::saveState ,
.
QSessionManager. -
28. 419

, allowinteractionO, ,
.
cancel ,
. setRestartHint ( ) ,
.
:
RestartifRunning ,
, ;
RestartAnyway
;
Restartimmediately
;
RestartNever .
QApplication::isSessionRestored ( ) ,
, (true)
(false).
, 28.10,
(. 28.2).

&** . ,
Exit the operating system to see the dialog box

. 28.2. ,

28.10 MyApplication QApplication.


commitData ( ) ,
.
. QApplication
MyApplication.

28.10. main.cpp

#include <QtWidgets>

/ / ======================================
class MyApplication : public QApplication {
public:
I/
MyApplication(int argc, char** argv)
: QApplication(argc, argv)
t
1

//
virtual -MyApplication()
420 V.

//
virtual void commitData(QSessionManager& sm) {
QMessageBox::information(0,
"Dialog,
"You are exiting operating system"

};

//
int main(int argc, char** argv)
{
MyApplication app(argc, argv);

QLabel lbl("Exit the operating system to see the dialog box", 0);
lbl.show();

return app.exec();
}

Qt ,
,
. .
, , /.
, QVariant.
value ( ) setvalue().

.
.
29

,
?
?
.

,
.
: .
, ,
.


(Clipboard)
, (
).
. ,
.
. , ,
: (cut), () (paste),
,
: <Ctrl>+<X>, <Ctrl>+<C> <Ctrl>+<V> .
Qt QClipboard.
,
.
QClipboard dataChanged ( ) ,
. ,
, . :
connect (qApp->clipboard ( ) , SIGNAL (dataChanged ( ) ) ,
pwgt , SLOT ( slotDataControl ( ) )
);

setTextf), setPixmapO,
set image ( ) setMimeData ( ) . :
QClipboard* pcb = QApplication: : clipboard!) ;
pcb->setText ("My Text") ;
422 V.


setMimeData ( ) .
, QMimesource.
QMimeSource , ,
.

text ( ) , image ( ) , pixmap ( ) mimeData ( )


. :
QClipboard* pcb = QApplication: :clipboard() ;
QString str = pcb->text ( ) ;
if .
( ! str isNull ( ) ) {
qDebugO "Clipboard Text: " str;
)

(drag & drop) , ,


, (
).
, , .
.
: ,
, , ,
( ) .
, .
Recycle Bin ()
Windows, .
Qwidget
, .
, ,
, . , QTextEdit (. 10)
.
Qt QDrag,
QMimeData. 1 Multipurpose
Internet Mail Extension ( ).
, , -
. , MIME- text/plain
, ASCII-, a text/html ,
, HTML.
image/*. , jpg MIME-
image/jpg. ,
, application/*.
. 29.1 .
, MIME Qt QMimeData.
:
setColorData ( ) ;
setimageData ( ) ;
29. 423

setText();
HTML setHtml();
() URL (Uniform Resource Locator,
)
seturls(). .

29.1. MIME-

MIME-

application/* ,

audio/* , : audio/wav

image/* , : image/png

model/* , , : model/vrml

text/* , : text/plain

video/* , : video/mpeg

, , ,
(, ).
? QMimeData
setData ( ) , ,
, QByteArray (. 4).
QMimeData formats ()
retrieveData().
:
(drag),
(drop).
, . . 29. 1
.

1 2

. 29.1.
424 V.

drag
mousePressEvent()
mouseMoveEvent ( ) . ,
. mouseMoveEvent ( )
.
( 29.1)
(. 29.2).

. 29.2.

Drag, 29.1, m ptDragPos,



. mousePressEvent ( )
, .
mouseMoveEvent ( ) . ,

, ,
, .
,
. ,
startDragDistance ( ) ( 4 ), ,
,
.
startDragO. QMimeData,
setText ( ) .
QDrag,
, .

!
,
.

. ,
, .
29. 425

setPixmapO ,
. ( )
. ,
, .
, Qt ::CopyAction,
Qt::MoveAction, Qt::LinkAction.
Qt::MoveAction.

29.1. Drag.h

#pragma once

#include <QtWidgets>

// ===========================================
class Drag : public QLabel {
Q_OBJECT
private:
QPoint m_ptDragPos;

void startDragO
{
QMimeData* pMimeData = new QMimeData;
pMimeData->setText(text());

QDrag* pDrag = new QDrag(this);


pDrag->setMimeData(pMimeData);
pDrag->setPixmap(QPixmap(":/imgl.png"));
pDrag->exec();
}

protected:
virtual void mousePressEvent(QMouseEvent* pe)
{
if (pe->button() == Qt::LeftButton) {
m_ptDragPos = pe->pos();
}
QWidget::mousePressEvent(pe);
}

virtual void mouseMoveEvent (QMouseEvent* pe)


{
if (pe->buttons() & Qt::LeftButton) {

int distance = (pe->pos() m_ptDragPos).manhattanLength();
if (distance > QApplication::startDragDistance()) {
startDrag();
}
}
QWidget::mouseMoveEvent(pe);
426 V.

public:
Drag(QWidget* pwgt = 0) : QLabel("This is draggable text", pwgt)
{
}
};

drop
( 29.2) ,
( ).
(. 29.3).

. 29.3. ,

,
Drop setAcceptDrops ( ) ,
true. ,
dragEnterEvent( ) dropEvent().
dragEnterEvent ( ) ,
(. . 29.1).
,
(, ,
<Ctrl>),
.
,
hasFormat().

MIME- , .
"text/uri-list".

acceptProposedActionO QDragEnterEvent
.
29. 427


QDragEnterEvent QDragMoveEvent (. . 14.1).
accept ignore ,
( ) .
QRect.
. , ,
, : accept(recto ).

dropEvent()
, . uris()
QMimeData urlList.
foreach QUrl::tostring() ,
("\") .
setText().

29.2. Drop.h

#pragma once

#include <QtWidgets>

// ======================================================
class Drop : public QLabel {
Q_OBJECT

protected:
virtual void dragEnterEvent(QDragEnterEvent* pe)
(
if (pe->mimeData()->hasFormat("text/uri-list")) {
pe->acceptProposedAction();

virtual void dropEvent(QDropEvent* pe)


{
QList<QUrl> urlList = pe->mimeData ()->urls();
QString str;
foreach(QUrl url, urlList) {
str += url.toStringO + "\n";
}
setText("Dropped:\n" + str);
l

public:
Drop(QWidget* pwgt = 0) : QLabel("Drop Area", pwgt)
(
setAcceptDrops(true);
428 V.


Qt , ,
, .
.
, .
mimeType,
,
. ,
, 29.3.

29.3.

MyDragClass::startDrag()
{
Qlmage img("mira.jpg");
QByteArray data;
QBuffer buf(sdata);
QMimeData* pMimeData = new QMimeData;

buf.open(QIODevice::WriteOnly);
img.save(&buf, "JPG");
pMimeData->setData("image/jpg", data);

QDrag* pDrag = new QDrag(this);


pDrag->setMimeData(pMimeData);
pDrag->exec(Qt::MoveAction);

29.3 ,
. , QMimeData; ;
setimageDataO,
, . ,
QMimeData, QByteArray QBuffer.
Qlmage::saved QBuffer,
(data). QMimeData::setData().
image/jpg
.
,

QByteArray, . ,
,
, MIME-. ,
. ,
,
. ( 29.4-29.13),
. 29.4, , ,
, .
29.

1] Widgetl |0-
1J Widgetl j
__
J
429

Widget is dropped Widget is dropped


ObjectName : Wldget2 ObjectName: Widgetl

. 29.4. ,

( 29.4) widget,
29.7-29.13.
,
setwindowTitle ( ) .
"widgetl" "Widget2" setObjectName().

29.4. main.cpp

#include <QApplication>
#include "Widget.h"

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


{
QApplication app(argc, argv);
Widget wgtl;
Widget wgt2;

wgtl.setwindowTitle("Widgetl");
wgtl.setObjectName("Widgetl");
wgtl.resize(200, 200);
wgtl.show();

wgt2.setwindowTitle("Widget2");
wgt2.setObjectName("Widget2");
wgt2.resize(200, 200);
wgt2.show();

return app.exec();
}

MIME- ( 29.5)
, widgetMimeData m pwgt.
mimeType ( ) MIME-, "application/widget".
: application ,
. : widget ,
. -
430 V.

setwidget ( ) . m pwgt
, setDataO,
MIME- QByteArray.
widget().

29.5. WidgetDrag.h. widgetMi menata

class WidgetMimeData : public QMimeData {


private:
QWidget* m_pwgt;

public:
WidgetMimeData() : QMimeData()
(
}

virtual -WidgetMimeData()
{
}

static QString mimeType()


{
return "application/widget";
}

void setwidget(QWidget* pwgt)


(
m_pwgt = pwgt;
setData(mimeType(), QByteArray());
}

QWidget* widget () const


(
return m_pwgt;
}

widgetDrag ( 29.6) ,
QDrag. setwidget ,
MIME- WidgetMimeData. setwidget ( )
(pwgt). setMimeData ( )
MIME- ( pmd).

29.6. WidgetDrag.h. WidgetDrag

class WidgetDrag : public QDrag {


public:
WidgetDrag(QWidget* pwgtDragSource = 0) : QDrag(pwgtDragSource)
(
I
29. 431

void setwidget(QWidget* pwgt)


{
WidgetMimeData* pmd = new WidgetMimeData;
pmd->setwidget(pwgt);
setMimeData(pmd);

};

, MIME- (
29.7). ,
QLabei. ,
. ,
.

29.7. Widget.h

#pragma once

#include <QPoint>
#include <QLabel>

/ / ================================================
class Widget : public QLabei {
Q_OBJECT
private:
QPoint m_ptDragPos;

void startDrag();

protected:
virtual void mousePressEvent(QMouseEvent* );
virtual void mouseMoveEvent (QMouseEvent* );
virtual void dragEnterEvent (QDragEnterEvent*);
virtual void dropEvent (QDropEvent* );

public:
Widget(QWidget* pwgt = 0);
};

, 29.8,
, true setAcceptDrops().

29.8. Widget.cpp.

Widget::Widget(QWidget* pwgt/*=0*/) : QLabei(pwgt)


{
setAcceptDrops(true);
432 V.

startDragO ( 29.9)
this. ,
, this setwidgeto.
( ) .

29.9. Widgetcpp. startDragO

void Widget : : startDrag ( )


{
WidgetDrag* pDrag = new Widget Drag (this) ;
pDrag->setWidget (this) ;
pDrag->exec (Qt : : CopyAction) ;
}

mouse PressEvent () ( 29.10) m ptDragPos


.

29.10. Widgetcpp. mousePressEvent

/virtual*/ void Widget ::mousePressEvent (QMouseEvent* pe)


{
if (pe->button ( ) == Qt: :LeftButton) {
m_ptDragPos = pe->pos ( ) ;
}
QWidget: : mousePressEvent (pe) ;
}

mouseMoveEvent ( ) ( 29. 1 1) .
, 29.1,
.

29.11. Widgetcpp. mouseMoveEvent ()

/virtual*/ void Widget ::mouseMoveEvent (QMouseEvent* pe)


{
if (pe->buttons ( ) & Qt: rLeftButton) {
int distance = (pe->pos() m_ptDragPos) .manhattanLength ( ) ;
if (distance > QApplication: : startDragDistance ( ) ) {
startDrag ( ) ;
}
}
QWidget: : mouseMoveEvent (pe) ;
}

dragEnterEvent ( ) ( 29.12)
, "application/widget ",
hasFormat ( ) .
WidgetMimeData : :mimeType ( ) .
29. 433

29.12. Widgetxpp. dragEnterEvent()

/virtual*/ void Widget::dragEnterEvent(QDragEnterEvent* pe)


{
if (pe->mimeData()->hasFormat(WidgetMimeData::mimeType())) {
pe->acceptProposedAction();

mimeData ( )
( 29.13). ,
, , WidgetMimeData.
, widget().
setText().

29.13. Widgetxpp. drqpEventO

/virtual*/ void Widget::dropEvent(QDropEvent* pe)


(
const WidgetMimeData* pmmd =
dynamic_cast<const WidgetMimeData*>(pe->mimeData());
if (pmmd) {
QWidget* pwgt = pmmd->widget();
QString str("Widget is dropped\n ObjectName:%1");
setText(str.arg(pwgt->objectName()));


, (
).
, .
.
(drag & drop)
. Drag & drop
,
( ).
.
, .
,
. , Windows
. ,
, ,
.
434 V.

Qt QDrag drag & drop


QMimeData .

,
mousePressEvent () mouseMoveEvent ( ) .
dragEnterEvent ( ) dropEvent ( ) , (
) setAcceptDrops ( ) , true.
Qt .
30

.
.

. !!! .

-8 .

,
. .

. ,
,
. , ,
100 , 98 %
. , , ,
, , , ,
?
, !
Qt-
:
1. ( ).
2. lupdate.
3. (
Qt Linguist).
4. lrelease ,
QTranslator.
.



, ,
. , ,
, tr ( ) ,
QObject.
436 V.

, , .
. tr()
. ,
,
. :
setText(tr("Yes"));

tr ( ) QString::arg():
setText(tr("User Name: %1").arg(strName));

, tr ( )
, , ,
, , . ,
,
. ,
. :
QLabel 1(tr("Location", "On the map"));
tr ( ) ,
, ,
, . :
QKeySequence keyseq(tr("CTRL+L"));

. -

tr() , .
:
int n = getDays();
QLabel 1 (tr("day(s): "Plural or singular", n));
, , ,
,
.

: 8, ,
internationalization, ,
18, .
localization ():
110.

, , .
, 2876,56 2,876.56,
2.876,56.
. :
QLocale english(QLocale::English, QLocale::UnitedKingdom);
QString str = english.toString(2876.56); // str = 2,876.56
QLocale german(QLocale::German, QLocale::Germany);
str = german.toString(2876.56); //str = 2.876,56

, , , ,
. ,
30. 437

.
:
qApp->setLayoutDirection(Qt::RightToLeft);

Iupdate
tr ()
. lupdate.
tr ( ) ,
. , tr ( ) ,
TS- (Translation Source, ) .
, 30.1 . 30.1,
, :
lupdate main.cpp -ts main_ru.ts main_de.ts


lupdate ,
.

. 30.1.

30.1. main.cpp

#include <QtWidgets>

int mainfint argc, char** argv)


{
QApplication app(argc, argv);
QLabel lbl(QObject::tr("Hello"));

lbl.show();
return app.exec();

XML,
:
<!DOCTYPE TSXTS>
<context>
<name>QObject</name>
<message>
<source>Hello</source>
<translation type="unfinished"x/translation>
</message>
</context>
</TS>
438 V.

. translation
type . ,
translation :
<translation>3flpaBCTByfi</translation>

.
:
TRANSLATIONS = main ru.ts main de.ts

Qt Linguist
.

. , , , ,
.
Qt Linguist Qt
. .

, . ,
.
Qt Linguist
(. 30.2):
linguist main_ru.ts


.
, <Ctrl> (
) <Shift> ( ).
Qt Linguist : Context, Strings, Sources and
Forms, Source text, Phrases and guesses Warnings.
:
Context ,
TS-. .
. Context
, . Item
, ( ),
( );
Strings (), ,
.
. ;
Source and Forms ( )
, ;
Source text ( ) .
, ,
.
, ;
30. 439

800 /Users/maxsehlee/engine/apps/GroupPhoto/PhotoGUN/yyy/main_ru.ts - Qt Linguist


Context
$ 0 Zi 1
Strings Sources and Forms
toww Hems If? Source lexi infinite <QtWidgets>
c? QObject 1/1 Hello
int mainOnt argc, char** argv)
{
QApplication app(argc, argv);
QLabel lbl(QObject::trCHello"));

Ibl.showO;
return app.execO;
}

| I
Source text
Hello
Russian translation

Russian translator comments

0 Phrases and guesses Q Warnings


Source phrase Translation Definition |

_ l/l MOD

. 30.2. Qt Linguist

Phrases and guesses ( )


;
Warnings () .
, ,
.
.
File | Save ( | ).
TS-
QM- (Messages file, ). File |
Release ( | ),
, Save ().

Irelease.
,
QM-
: lupdate, Qt Linguist lrelease.
440 V.

(TS-), ,
QM-:
lrelease myproject.pro

QM- QTranslator.
QTranslator .
QM-, QTranslator
load ( ) . QM-
. , 30.2,
, Hello (. 30.3).

. 30.3.

30.2 QTranslator. load ( )


main_ru.qm, .
, . ,
, , , QM-
, . installTranslator ( )
QApplication .

30.2. main.cpp

int mainfint argc, char** argv)


1
QApplication apptargc, argv) ;
QTranslator translator;
ptranslator.load("main_ru.qm", ".") ;
app. installTranslator (stranslator) ;

QLabel 1 (QObject: :tr ("Hello") ) ;


1 . show ( ) ;
return app . exec ( ) ;
1

,
Qt , , ,
WebKit . .
. QM- Qt
.
translations. , ,
: Qt,
( 30.3).

30.3. Qt

QTranslator qtTranslator;
.
qtTranslator load (QString (" : /translations/qt_" ) +
QLocale : : system ( ) . name ( ) ) ;
30. 441

qApp->installTranslation(sqtTranslator);

QTranslator appTranslator;
appTranslator.load(QString(":/translations/app_") +
QLocale::system().name());
appTanslator.load("main_ru.qm", ".");
qApp->installTranslator(sappTranslator);

QM- ,
30.3. QM-
,
.




.
, . .
,
QSettings .

.
,
. ,
,
. ,

. ,
, , ,
,
.
QSettings.
,
,
. ,
.
.
,
. ,

. , QCoreApplication::
installTranslator () QEvent::LanguageChange,
, QWidget.
,
. 30.4.
442 V.

30.4.

void MyLabel::changeEvent(QEvent* )
{
if (pe->type() == QEvent::LanguageChange) {
retranslateUi();

void MyLabel::retranslateUi()
{
setWindowTitle(tr("Current Language" ));
setText(tr("Hello"));

30.4
QWidget::changeEvent(), retranslateUi().
.

, :
void MyProgram::switchLanguage(int n)
{
QTranslator translator;

switch (n) {
case RUSSIAN:
translator.load("myprogram_ru.qm"
break;
case GERMAN:
translator.load("myprogram_de.qm"
break;
}
qApp->installTranslator(stranslator);
}

, (,
),
.
QLocate::system(). QLocate,
name() "_". ,
: "en_us".


ISO 639-1, ISO 3166-1.

"_"
. , :
QTranslator translator;
QString str = QLocale::system().name();
30. 443

if (str == "en_US") {
translator.load("myprogram_us.qm" //
//
}
else if (str == "de_CH") {
translator.load("myprogram_de.qm" //
//
}
else if (str == "ru") {
translator.load("myprogram_ru.qm" //

qApp->installTranslator(stranslator);


,
,
. , ,
. ,
, Google Translte (http://translate.google.com), Yahoo BabelFish (http://babelfish.
yahoo.com), ,
, , . ,
(, ) , , .

. 30.4. Pootle
444 V.

. ,
.
Qt Linguist.
,
Pootle (http://translate.sourceforge.net). ,
. 30.4, .
, ts,
xlf.
lconvert, Qt.


. tr ( ) QObject . -,
lupdate , . -
, .
, .
,
, : ,
, , , ,
. .
, lupdate,
ts (TS-) C++.
Qt Linguist.
QM-.
lrelease.
QM- QTransiator ioad().

installTranslator ( ) QCoreApplication.

, , .
31

(Menu)?
! (File)

.

,
. :
;
;
(), ;
.
Qt QMenu.
QMenu. .
( QAction, . 34).

. , ,
, hovered ( ) ,
- ,
.


,
. . 31.1 .
.
, , ,
( <Alt>
).
, ,
.
, , ,
. QMenuBar
QMenuBar.
446 V.

, , ,
, .
, About Qt ( Qt), , . 31.1,
<Ctrl>+<Q>.
. . 31.1.

31.1.

<Esc> <Ctrl>+<Z>

<F1> <Ctrl>+<X>

<Shift>+<F1> <Ctrl>+<C>

<Ctrl>+<N> <Ctrl>+<V>

<Ctrl>+<0> <Ctrl>+<F4>
MDI-

<Ctrl>+<P> <Ctrl>+<F6>

MDI-

<Ctrl>+<S> <Shift>+<Ctrl>+<F6>

MDI-

,
. ,
, ( )
<Alt>. , Exit () <Alt>+<E>
(. . 31.1).
:
31. 447

<Alt> ;
, ;
. ,
About Qt ( Qt), Menu ()
<Alt>+<M>, <Alt>+<A>.
SubMenu () (. . 31.1) ,
, Test ().
, , .
,
.

, .
.
.
() .
.
, .
,
.
, .
, , ,
. , ,
.
31.1 , . 31.1.

31.1. main.cpp

#include <QtWidgets>

int main(int argc, char** argv)


{
QApplication app(argc, argv);

QMenuBar mnuBar;
QMenu* pmnu = new QMenu("&Menu");

pmnu->addAction("&About Qt",
&app,
SLOT(aboutQt()),
Qt::CTRL + Qt::Key_Q
);

pmnu->addSeparator();

QAction* pCheckableAction = pmnu->addAction("sCheckableltem");


pCheckableAction->setCheckable(true);
pCheckableAction->setCheeked(true);
448 V.

pmnu->addAction(QPixmap(":/img4.png" ), "Slconltem");

QMenu* pmnuSubMenu = new QMenu("SSubMenu", pmnu);


pmnu->addMenu(pmnuSubMenu);
pmnuSubMenu->addAction("&Test");

QAction* pDisabledAction = pmnu->addAction("SDisabledltem");


pDisabledAction->setEnabled(false);

pmnu->addSeparator();

pmnu->addAction("&Exit", &app, SLOT(quit()));

mnuBar.addMenu(pmnu);
mnuBar.show();

return app.exec();
}

,
.
QMenu. , QMenuBar
pmnuBar , , QMenu pmnu (. 31.1).

addActionO . addActionO
QAction. , .
setCheckable ( ) ( pCheckableAction)
. setCheckedO
. true,
, .
addActionO . ,
, &.
,
, .
, ,
. .
.
About Qt ( Qt) <Ctrl>+<Q>.
, ,
aboutQt ( ) .
. 14.2.
addSeparator ( ) .
(pDisableAction) ,

setEnabled().
addActionO
.
31. 449


Qt , ,
(Tear-off menu). ,
, ,
(. 31.2). , ,
.

TearOffMenu 3

. 31.2.

( 3 1.2), setTearOffEnabled()
pmnu, true,
.

31.2. main.cpp.

#include <QtWidgets>

int main(int argc, char** argv)


{
QApplication app(argc, argv);

QMenuBar pmnuBar;
QMenu* pmnu = new QMenu("SMenu");

pmnu->setTearOffEnabled(true);

pmnu->addAction("Itemsl");
pmnu->addAction("Items2");
pmnu->addAction(Items3");
pmnu->addAction("SExit", Sapp, SLOT(quit()));

pmnuBar.addMenu(pmnu);
pmnuBar.show();

return app.exec();
450 V.


.
, .
, , QMenu.
, QMenuBar. . 31 .3
(. 31.1) ,
. :
Red (), Green () Blue (),
.

. 31.3.

ContextMenu 3 1.3
m pmnu. addActionO .
connect () triggered(QAction*) slotActivated(QAction*).
.
. , ContextMenu
QTextEdit,

HTML QTextEdit::setHtml().
, &,
QString::remove().
strColor.

QWidget ::contextMenuEvent ( ) ( )
. ( ) ,
globalPos ( ) .
QPoint,
.

31.3. main.cpp.

#pragma once

#include <QtWidgets>

,
/ =======================================
class ContextMenu : public QTextEdit {
Q_OBJECT
private:
QMenu* m_pmnu;
31. 451

protected:
virtual void contextMenuEvent(QContextMenuEvent* pe)
{
m_pmnu->exec(pe->globalPos());
}

public:
ContextMenu(QWidget* pwgt = 0)
: QTextEdit(pwgt)
{
setReadOnly(true);
m_pmnu = new QMenu(this);
m_pmnu->addAction("&Red");
m_pmnu->addAction("&Green");
m_pmnu->addAction("&Blue");
connect(m_pmnu,
SIGNAL(triggered(QAction*)),
SLOT(slotActivated(QAction*))

public slots:
void slotActivated(QAction* pAction)
{
QString strColor = pAction->text().remove("&");

setHtml(QString("<BODY BGCOLOR=%lx/BODY>").arg(strColor));

,
, .
: , ,
.
,
,
,
, .
,
. , ,
, , , ,
.
32

Windows
:
Windows:
?

: !
Windows: ?

,
. ,
.
.
:
;
;
.


,
,
. , ,
, .
,
, .
:
,
.
: Ok, Cancel () Apply ();
,
(. 8). ;
.
,
(. 11);
,
;
32. 453

.

;
Help (),
;
, , ,
: Open... (...). , ,
;
.
;
, .
,
;
.
. , ,
. , ,
;
,
, .
, ,
<Alt>, .

QDialog
QDialog ,
Qt (. . 5.1).
, ,
QDialog, ,
. :
;
.
,
QDialog: isetModal () QDialog::isModal () . true
, a false .


.
, , ,
. ,
.
.
,
,
. (),
,
454 V.

QDialog::Accepted QDialog::Rejected, Ok
Cancel ().
.

. :
MyDialog* pdlg = new MyDialog(&data);
if (pdlg->exec() == QDialog::Accepted) {
// Accepted
//
Data data = pdlg->getData();

delete pdlg;


,
. ,
, ,
. , ,
,
. ,
, .
show ( ) ,
. show ()
. hide ( ) .
,
. , show () hide()
, .
Close (),
.

!
Mac OS X
. ,
show () , .
show() raise ()
activateWindow().


( 32.1-32.6), . 32.1,
.
Press Me ( ) (. . 32.1, ),
First Name () Last Name () (. . 32.1,
).
32.1 startDialog,
.
32. 455

. 32.1.

32.1. main.cpp

#include <QApplication>
#include "StartDialog.h"

int main(int argc, char** argv)


{
QApplication app(argc, argv);
StartDialog startDialog;

startDialog.show();

return app.exec();
}

StartDialog ( 32.2) QPushButton.


clicked () connect () slotButtonClickedO .
inputDialog, .


, , .
.

if .
, ( )
. , Ok,
.
, ,
.

32.2. StartDialog.h

#pragma once

#include <QtWidgets>
#include "InputDialog.h"

//
class StartDialog : public QPushButton {
Q OBJECT
456 V.

public:
StartDialog(QWidget* pwgt = 0) : QPushButton("Press Me", pwgt)
{
connect(this, SIGNAL(clicked()), SLOT(slotButtonClicked()));
}

public slots:
void slotButtonClicked()
(
InputDialog* plnputDialog = new InputDialog;
if (plnputDialog->exec() == QDialog::Accepted) {
QMessageBox::information(0,
"Information",
"First Name: "
+ pInputDialog->firstName()
+ "\nLast Name: "
+ pInputDialog->lastName()
);
}
delete plnputDialog;
}
};

QDialog,
32.3. InputDialog :
m ptxtFirstName m ptxtLastName ,
: firstName() lastName().

32.3. InputDialog.h

#pragma once

#include <QDialog>

class QLineEdit;
// ==========================
class InputDialog : public QDialog {
Q_OBJECT
private:
QLineEdit* m_ptxtFirstName;
QLineEdit* m_ptxtLastName;

public:
InputDialog(QWidget* pwgt = 0);

QString firstNameO const;


QString lastName () const;
32. 457

?,
.
,
Qt::WindowTitleHint Qt::WindowSystemMenuHint.
,
( 32.4).
Cancel ().
clicked () Ok Cancel () accept () rejected!)
. , ( )
Ok QDiaiog::Accepted, Cancel ()
QDialog::Rejected.

32.4. InputDialog.cpp. InputDialog ( )

InputDialog::InputDialog(QWidget* pwgt/*= 0*/)


: QDialog(pwgt, Qt::WindowTitleHint | Qt::WindowSystemMenuHint)
{
m_ptxtFirstName = new QLineEdit;
m_ptxtLastName = new QLineEdit;

QLabel* plblFirstName = new QLabel("&First Name");


QLabel* plblLastName = new QLabel("&Last Name");
plblFirstName->setBuddy(m_ptxtFirstName);
plblLastName->setBuddy(m_ptxtLastName);

QPushButton* pcmdOk = new QPushButton("&Ok");


QPushButton* pcmdCancel = new QPushButton("sCancel");

connect(pcmdOk, SIGNAL(clicked()), SLOT(accept()));


connect(pcmdCancel, SIGNAL(clicked()), SLOT(reject()));

//Layout setup
QGridLayout* ptopLayout = new QGridLayout;
ptopLayout->addWidget(plblFirstName, 0, 0);
ptopLayout->addWidget(plblLastName, 1, 0);
ptopLayout->addWidget(m_ptxtFirstName, 0, 1);
ptopLayout->addWidget(m_ptxtLastName, 1, 1);
ptopLayout->addWidget(pcmdOk, 2,0);
ptopLayout->addWidget(pcmdCancel, 2, 1);
setLayout(ptopLayout);

firstName () ( 32.5).

32.5. InputDialog.cpp. firstName ()

QString InputDialog::firstName() const


{
return m_ptxtFirstName->text();
)
458 V.

firstName () ( 32.6).

32.6. InputDialog.cpp. lastName ()

QString InputDialog::lastName() const


{
return m_ptxtLastName->text();
}


,
, , . .
,
Qt.
,
, , .


,
, ,
. QFileDialog
(. 32.2)
.
, ,
. QFileDialog QDialog.
QFileDialog.
QFileDialog :
getOpenFileName() .
QString, (. . 32.2);
getOpenFileNames ( ) .
QStringList, ;
getSaveFileName .
QString;
getExistingDirectory()
.
QString, .
-,
, , .
getOpenFileName () (. . 32.2).
, , ( ),
. :
QString str = QFileDialog::getOpenFileName(0, "Open Dialog", "*.cpp *.h");

32.7 , getSaveFileName(),
.
32. 459

_ Open Dialc
is k (:) Qt 41.2 src gui

| E-mails Document s Pictures Music


dialogs | ||| Search P -
Show results for All Kinds >> n \J\ C:\Qt\4... Adialcgs

Favorite Links Name Date modified Type Size


[~1 qdialog_p,h 6/19/2006 3:45 AM H File 2.24 KB
(Empty)
1 1 qerrormessage.cpp 6/19/2006 3:45 AM CPP File 7.78 KB
1 1qerrormessage.h 6/19/2006 3:45 AM H File 1.78 KB
,_, qfiledialog.cpp 6/19/2006 3:45 AM CPP File 812 KB !
l_i qfiledialcg.h 6/19/2006 3:45 AM HFile 10.9 KB
[_, qfiledialcg_p.h 69/2006 3:45 AM H File 7.02 KB
,_, qfiledialog_win.cpp 6/19/2006 3:45 AM CPP File 24.3 KB
i_ j qfontdialog.cpp 6/19/2006 3:45 AM CPP File 249 KB
j_ j qfontdialog.h 6/19/2006 3:45 AM HFile 2.67 KB
[_, qinputdialog.cpp 6/19/2006 3:45 AM CPP File 142 KB
Folders qinputdialoq.h 6/19/2006 3:45 AM H File 4.55 KB

: qfiledialog *.cpp *-h


]
upen Cancel

. 32.2.

32.7.

QPixmap pix(320, 200);


QString strFilter;
QString str =
QFileDialog::get Save FileName (0,
t r ("Save Pixmap" ),
"Pixmap",
"*.png ;; *.jpg ;; *.bmp",
sstrFilter
);
if ( Istr.isEmpty() ) {
if (strFilter.contains ("jpg")) {
pix.save (str, "JPG");
}
else if (strFilter.contains ("bmp") ) {
pix.save(str, "BMP");

else {
pix.save(str, "PNG");
}

, - .
32.7
320x200 ( pix). strFormat
460 V.

.
getSaveFileName () .
: , "Save Pixmap",
"Pixmap", ,
; ;
. , ,
( strFilter).
str , ,
strFilter QString::contains ()
.
QPixmap::save ( ) . JPG BMP ,
PNG.
getExistingDirectory ()
(. 32.3). :
QString str = QFileDialog::getExistingDirectory(0, "Directory Dialog", "");

. 32.3.


,
(. 32.4).
pro- QtPrintSupport. :
QT += printsupport

QPrintDialog,
QPrinter (. 24) ,
. :
QPrinter printer;
QPrintDialog* pPrintDialog = new QPrintDialog(sprinter);
if (pPrintDialog->exec() == QDialog::Accepted) {
//
}
delete pPrintDialog;
32. 461

Print
General

Select Printer

|jp Microsoft XPS Document Writer

Status: Ready I I Pnnt to file Pceferences


Location:
Comment: Find Printer-

Page Range
All
Selection Current
1' Pages:

Print Cancel Apply

. 32.4.


QColorDialog (. 32.5).
, getColor ( ) .

. 32.5.
462 V.

.
. getColorO
QColor. , : Cancel
(), isvalido QColor.
true , ,
Cancel ().
:
QColor color = QColorDialog::getColor(blue);
if (!color.isValid()) {
// Cancel
)



, (. 32.6).
QFontDiaiog, QFontDialog.

. 32.6.

,
QFontDialog::getFont () .
. true ,
,

false. QFont,
.
getFont ( ) , .
:
bool bOk;
QFont fnt = QFontDialog::getFont(&bOk);
32. 463

if (!) {
// Cancel
}



. QinputDialog. ,
,
QLineEdit, , ?
, , ,
.
QinputDialog
:

getText ( ) ;
getinteger ( ) ;
getDouble() ;
getitem ( ) .
,
, ,
. , :
getinteger () getDouble ()
( ), :
( -2147483647) (
2 147483 647) ;
getText ( ) ,
( );
get item( ) (QStringList),
( ),
(
).
:
, , : Cancel
(), (. 5).
, (. 32.7) :
bool bOk;
QString str = QinputDialog::getText(,
"Input",
"Name:",
QLineEdit::Normal,
"Tarja",
&bOk

if (!bOk) {
// Cancel
464 V.

. 32.7.

QLineEdit::Normal QLineEdit::Password,
.


- Qt
QProgressDialog, QDialog.

. Cancel ()
. canceled (),
, .
,
, ,
. , ,
, setMinimumDuration ( ) .

setTotalsteps ( ) .
setProgress().

. 32.8.

, . 32.8, :
int = 100000;
QProgressDialog* pprd =
new QProgressDialog("Processing the data..., "sCancel", 0, n);

pprd->setMinimumDuration(0);
pprd->setWindowTitle("Please Wait");

for (int i = 0; i < n; ++i) {


pprd->setValue(i);
qApp->processEvents();
32. 465

if (pprd->wasCanceled()) {
break;
}
}
pprd->setValue(n);
delete pprd;
QProgressDialog
.
Cancel ().
,
. , , .
, (. 5).
setMinimumDuration ( ) 0, ,
. setwindowTitle ( )
. , (
for), setValueO, .
processEvents ( )
,
(. 14). if
wasCanceled ( ) , Cancel (),
, .
reset ( ) ,
. ,
, setAutoReset ( ) true.
setAutoClose ( ) ,
true.



, .
: Next () Back ().
,
, ,
.

QWizard
addPage().
QWizardPage, setTitle ()
, .
,
. 32.8
, (. 32.9).

32.8.

class Wizard : public QWizard {


private:
QWizardPage* createPage(QWidget* pwgt, QString strTitle)
466 V.

{
QWizardPage* ppage = new QWizardPage;
ppage->setTitle(strTitle);

QVBoxLayout* playout = new QVBoxLayout;


playout->addWidget(pwgt);
ppage->setLayout(playout);

return ppage;
}

public:
Wizard::Wizard(QWidget* pwgt = 0) : QWizard(pwgt)
(
addPage(createPage(new QLabel("<Hl>Label 1</H1>"), "One"));
addPage(createPage(new QLabel("<Hl>Label 2</Hl>"), "Two"));
addPage(createPage(new QLabel("<Hl>Label 3</Hl>"), "Three"));
}
};

. 32.9.



,
QMessageBox. ,
.
32. 467


. , QMessageBox, .
, .
QMessageBox ,
.
: , ,
. .
,
.
.
, . 32.10, :
QMessageBox* pmbx =
new QMessageBox(QMessageBox::Information,
"MessageBox",
"<b>A</b> <i>Simple</i> <u>Message</u>",
QMessageBox::Yes | QMessageBox::No I
QMessageBox::Cancel
);
int n = pmbx->exec();
delete pmbx;

if (n == QMessageBox::Yes) {
// Yes
}

. 32.10.

.
, (. 32.1).
, ,
HTML. ,
(. 32.2), , ,
.
Yes, No Cancel. ,
Cancel (). ,
<Escape>,
Cancel.
,
, . ( )
QMessageBox
. ( ) -
468 V.

, . delete
. if
Yes ().
, , ,
QMessageBox. setText (),
setButtonText ( ) . setButtonText ( )
, . 32.2,
. setwindowTitle () .
set icon () ,
, . 32.1.
, ,
QPixmap setlconPixmap ( ) .

32.1.


Noicon 0
Information 1
V
Warning 2

Critical 3

Question 4
V
32.2. QMessageBox

NoButton No YesAll

Ok Abort NoAll

Cancel Retry Escape

Yes Ignore Default


.
information
, . 32.11:
QMessageBox: : information (0, "Information", "Operation Complete");

, (. . 32.2).
32. 469

. 32.11. . 32.12.


(. 32.12)
warning ( ) QMessageBox.
:
int n = QMessageBox: : warning (,
"Warning",
"The text in the file has changed"
"\n Do you want to save the changes?",

QMessageBox: : Yes I QMessageBox: :No,


QMessageBox: :Yes
);
if (n == QMessageBox: :Yes) {
// Saving the changes !
}

warning ( ) (
), , .
( Yes No). ,
( Yes).
<Escape>, warning () QMessageBox: : Escape.
Yes ().


, -
(. 32.13).
critical ( ) , ,
, . :
int n = QMessageBox: : critical (,
"Attention ,
"This operation will make your "
"computer unusable, continue?",
QMessageBox: : Yes I QMessageBox :: No I
QMessageBox: : Cancel
);
if (n == QMessageBox: :Yes) {
// Do it !
)
470 V.

. 32.13. . 32.14.


, ,
about ( ) QMessageBox. ,
: , ,
. . (. 32.14).
.
, ,
:
QMessageBox::about (0, "About", " Program Ver. 1.0");

About Qt
About Qt ( Qt) QMessageBox
aboutQt { ) . .
, .


About Qt
This program uses Qt version 5.3.1.
Qt is a C++ toolkit for cross-platform application development.

Qt provides single-source portability across all major desktop operating systems. It is also available for
embedded Linux and other embedded and mobile operating systems.
Qt is available under three different licensing options designed to accommodate the needs of our
various users.

Qt licensed under our commercial license agreement is appropriate for development of proprietary/
commercial software where you do not want to share any source code with third parties or otherwise
cannot comply with the terms of the GNU LG PL version 2.1 or GNU GPL version 3.0.
Qt licensed under the GNU LGPL version 2.1 is appropriate for the development of Qt applications
provided you can comply with the terms and conditions of the GNU LGPL version 2.1.

Qt licensed under the GNU General Public License version 3.0 is appropriate for the development of Qt
applications where you wish to use such applications in combination with software subject to the terms
of the GNU GPL version 3.0 or where you are otherwise willing to comply with the terms of the GNU GPL
version 3.0.
Please see ot.diQia.com/Product/Licensing for an overview of Qt licensing.
Copyright (C) 2014 Digia Pic and/or its subsidiary(-ies) and other contributors.

Qt and the Qt logo are trademarks of Digia Pic and/or its subsidiary(-ies).

Qt is developed as an open source project on qt-proiect.org.


Qt is a Digia product. See qt.diqia.com for more information.
OK

. 32.15. About Qt
32. 471

Qt. . 32.15,
. :
QMessageBox::aboutQt(0);


QErrorMessage,
QMessageBox, .
.
showMessage ( ) , . :
(new QErrorMessage(this))->showMessage("Write Error");

. 32.16, , ,
.

, .
, .

. 32.16.

,
. ,
QDialog.

, . ,
, ,
.
: .

. .
,
.
. ,
, .

472 V.

. , ,
, ,
.
,
,
, . .
,
,
, , ,
?
33

.
, , .
:
, ...
,
, , .
.
.
,


, .
:
;
;
(Online Help).


, , , ,

, (. 33.1).
(tooltip) , , .
, , , ,
.
,
- ,
. ,
, , .
,
. ,
, .
, Cancel ()
.
, setToolTip():
QPushButton* pcmd = new QPushButton("&Ok");
pcmd->setToolTip("Button");
474 V.

eon

I 2kr v I
*
Button | My Tool Tip
. 33.1. . 33.2.

, setToolTipO
.

(. 33.2), ( 33.1).
QLabel ,
setToolTip().

event (),
QEvent::ToolTip.
QHelpEvent,
.
toolTip ( ) .
, show ( ) . -
, hide()
, 3 . Mywidget
.
Qt::ToolTip. ( main())
Mywidget
setToolTip().

33.1. main.cpp

class Mywidget : public QWidget {


private:
QLabel* m_plblToolTip;

protected:
virtual bool event(QEvent* pe)
{
if (pe->type() == QEvent::ToolTip) {
QHelpEvent* peHelp = static_cast<QHelpEvent*>(pe);
m_plblToolTip->move(peHelp->globalPos());
m_plblToolTip->setText(toolTip());
m_plblToolTip->show();
QTimer::singleShot(3000, m_plblToolTip, SLOT(hide()));

return true;
}

return QWidget::event(pe);
33. 475

public:
MyWidget(QWidget* pwgt = 0) : QWidget(pwgt)
{
m_plblToolTip = new QLabel;
m_plblToolTip->setWindowFlags(Qt::ToolTip);

};

//
int main(int argc, char** argv)
{
QApplication app(argc, argv);

MyWidget mw;
mw.setFixedSize(70, 70);
mw.setToolTip("<Hl>My Tool Tip</Hl>);
mw.show();

return app.exec();
}


,
. Whats this ( )
.
, ,
, .
, ? .
<Shift>+<Fl>.
( 33.2) . ?
,
(. 33.3).


Please press the 7-Button

. 33.3. Whats this

,
| () Qt::WindowContextHelpButtonHint
? (. 5).
Whats this ( ) setwhatsThis ( ) .
33.2, , setwhatsThis () ,
HTML.
476 V.

33.2. main.cpp

#include <QtWidgets>

int main(int argc, char** argv)


{
QApplication app(argc, argv);

QLabel 1 ("Please press the ?-Button"(


0,
Qt::WindowTitleHint I Qt::WindowSystemMenuHint
I Qt::WindowContextHelpButtonHint
);

1 .setWhatsThis("<I>This is the Label</IXBRXB>Class QLabel</B>");

1 .show();

return app.exec();
}

(Online Help)
,
.
, Help
() <F1>.
HTML, , ,
, , .
, HTML
.
.
QTextBrowser (. 33.4),
HTML. ( 33.3 33.4)
.
, 33.3,
helpBrowser.
, .

33.3. main.cpp

#include <QApplication>
#include "HelpBrowser.h"

int main (int argc, char** argv)


{
QApplication app(argc, argv);
HelpBrowser helpBrowser(":/", "index.htm");
33. 477

helpBrowser.resize(400, 300);
helpBrowser.show();

return app.exec();
}

. 33.4.

HelpBrowser ( 33.4)
: pcmdBack, pcmdHome pcmdForward.
connect () clicked ()
QTextBrowser: backwardO, home forwardO.
. connect ()
backwardAvailable(bool) forwardAvailable(bool) QTextBrowser
setEnabled(bool ) ( pcmdBack pcmdForward).
, , .
setSearchPath ( ) ,
. setSource ( ) .
(pvbxLayout) (phbxLayout)
.

33.4. HelpBrowser.h

#include <QtWidgets>

/ / =================================
class HelpBrowser : public QWidget {
Q OBJECT
478 V.

public:
HelpBrowser(const QStrings strPath,
const QStrings strFileName,
QWidget* pwgt =0
) : QWidget(pwgt)
{
QPushButton* pcmdBack = new QPushButton("");
QPushButton* pcmdHome = new QPushButton("Home");
QPushButton* pcmdForward = new QPushButton("");
QTextBrowser* ptxtBrowser = new QTextBrowser;

connect(pcmdBack, SIGNAL(clicked()),
ptxtBrowser, SLOT(backward())
);
connect(pcmdHome, SIGNAL(clicked()),
ptxtBrowser, SLOT(home())
);
connect(pcmdForward, SIGNAL(clicked()),
ptxtBrowser, SLOT(forward())
);
connect(ptxtBrowser, SIGNAL(backwardAvailable(bool)),
pcmdBack, SLOT(setEnabled(bool))
);
connect(ptxtBrowser, SIGNAL(forwardAvailable(bool)),
pcmdForward, SLOT(setEnabled(bool))
);

ptxtBrowser->setSearchPaths(QStringList() strPath);
ptxtBrowser->setSource(QString(strFileName));

//Layout setup
QVBoxLayout* pvbxLayout = new QVBoxLayout;
QHBoxLayout* phbxLayout = new QHBoxLayout;
phbxLayout->addWidget(pcmdBack);
phbxLayout->addWidget(pcmdHome);
phbxLayout->addWidget(pcmdForward);
pvbxLayout->addLayout(phbxLayout);
pvbxLayout->addWidget(ptxtBrowser);
setLayout(pvbxLayout);
}
};


.
: ,
(Online Help).
33. 479

,
, . ,
.
,

.

. , ,
HTML,
.
QTextBrowser.
34

,
SDI- MDI-
,
.
IBM

, ,
. . , Qt ,
.

QMainWindow
QMainWindow , (. 34.1),
, ,

(. 31), , ,
. . ,
, .
, . 34.1, ,
, . ,
. .
.
QMainWindow: rmenuBar ( )
:
QMenu* pmnuFile = new QMenu("&File");
pmnuFile->addAction("&Save");

menuBar()->addMenu(pmnuFile);

, :
File () : New (),
Open (), Save (), Print () Quit ();
Edit () : Cut (),
(), Paste (), Undo (), Redo (), Find (
), Replace () Delete ();
View () ,
. , Zoom () .
34. , SDI- MDI- 481

,
, , ;
Help ()
(. 33). , ,
. ,
About ( ) , ,
.

. 34.1.

,
QMainwindow::centralwidget ( ) , QWidget.
QMainWindows: isetCentralwidget ()
.
QMainwindow::statusBar() .
,
(. . 34.1), , ,
.
QSizeGrip. (QMainwindow) ,
.

QAction
QAction ,
. , ,
,
482 V.

. .
. ,
,
, .
QAction
. , File | New ( | )
, .
, ,
.
QAction :
;
;
;
;
;
;
.
QAction
. :
QAction* pactSave = new QAction("file save action", 0);
pactSave->setText("&Save");
pactSave->setShortcut(QKeySequence("CTRL+S"));
pactSave->setToolTip("Save Document");
pactSave->setStatusTip("Save the file to disk");
pactSave->setWhatsThis("Save the file to disk");
pactSave->setIcon(QPixmap(":/img4.png"));
connect(pactSave, SIGNAL(triggered()), SLOT(slotSave()));
QMenu* pmnuFile = new QMenu("&File");
pmnu->addAction(pactSave);
QToolBar* ptb = new QToolBar("Linker ToolBar");
ptb->addAction(pactSave);

addAction() .
QMenu ( pmnuFile)
QToolBar ( ptb).


(Tool )
.
, , , , .
, ,

.
34. , SDI- MDI- 483

, ,
. Qt
QToolBar, QToolBar.
, , , ,
.
,
addAction ( ) , .
, .

.

(. 33) .
,
.

,
.
QToolBar addwidget().
( 34.1),
. 34.2,
.
.
QMainWindow.

. 34.2.

Mainwindow, 34.1, QMainwindow.


addToolBarO
, createToolBar ( ) Mainwindow.
addToolBarO
. createToolBar ( )
addAction ( ) , :
,
(. 19). QPixmap;
( );
slotNoimpl( ) ,
Not implemented ( ).
addSeparator().

34.1. MainWindow.h

#pragma once

#include <QtWidgets>
484 V.

// ========================================================
class MainWindow : public QMainWindow {
Q_OBJECT
public:
MainWindow(QWidget* pwgt = 0) : QMainWindow(pwgt)
{
addToolBar(Qt::TopToolBarArea, createToolBar());
addToolBar(Qt::BottomToolBarArea, createToolBar());
addToolBar(Qt::LeftToolBarArea, createToolBar());
addToolBar(Qt::RightToolBarArea, createToolBar());
}

QToolBar* createToolBar()

QToolBar* ptb = new QToolBar("Linker ToolBar");

ptb->addAction(QPixmap(":/imgl.png"), "1", this, SLOT(slotNoImpl()));


ptb->addAction(QPixmap(":/img2.png"), "2", this, SLOT(slotNoImpl()));
ptb->addSeparator();
ptb->addAction(QPixmap(":/img3.png"), "3", this, SLOT(slotNoImpl()));
ptb->addAction(QPixmap(":/img4.png"), "4", this, SLOT(slotNoImpl()));

return ptb;
}

public slots:
void slotNoImpl()
{
QMessageBox::information(0, "Message", "Not implemented");

.
QDockwidget. , ,
, ,

, ,
. . 34.1 () ,
.
QMainWindow :

QDockwidget* pdock = new QDockwidget("MyDock", this);


QLabel* plbl = new QLabel("Label in Dock", pdoc);
pdock->setWidget(plbl);
addDockWidget(Qt::LeftDockWidgetArea, pdock);

( pdock)
, : MyDock.
34. , SDI- MDI- 485

( pibi)
setwidget ( ) .
QMainWindow: : addDockWidget ( ) . ,
, : Qt: :LeftDockwidgetArea,
. ,
setAllowedAreas () . ,
- , ,
,
:
pdock->setAllowedAreas (Qt : : BottomDockWidgetArea
I Qt : : TopDockWidgetArea
);

- .
,
. -, ,
. set Features () .
, - ,
:
pdock->setFeatures (QDockWidget: : DockWidgetMovable
| QDockWidget: : DockWidgetFloatable


, ,
,
.
QStatusBar, QStatusBar.
:
showMessage ( ) .
clearMessage () . showMessage ( )
,
.
;
(,
).
. ,
- ,
. ,
addwidgeto.
removewidget ( ) ;
, .
,
, <Caps Lock>, <Num Lock>,
<Insert> . . addPermanentwidget ( ) ,
.
486 V.

( 34.2) ,

(. 34.3).
34.2 Mainwindow QMainwindow.
, m plblx m plblY.
addwidget().

. 34.3. ,


mouseMoveEvent ( ) .
( ) ( ) ( ).

34.2. MainWindow.h

#pragma once

#include <QtWidgets>

/ / ========================================================
class MainWindow : public QMainWindow {
Q_OBJECT
private:
QLabel* m_plblX;
QLabel* m_plblY;

protected:
virtual void mouseMoveEvent(QMouseEvent* pe)
{
m_plblX->setText(X=" + QString().setNum(pe->x()));
m_plblY->setText("Y=" + QString().setNum(pe->y()));
}

public:
Mainwindow(QWidget* pwgt = 0) : QMainwindow(pwgt)
{
setMouseTracking(true);
34. , SDI- MDI- 487

_1 = new QLabel(this);
m_plblY = new QLabel(this);
statusBar()->addwidget(m_plblY);
statusBar()->addwidget(_1);

};


(Splash Screen).
, ,
.
.
Qt QSplashScreen.
main ( ) ( ) . ,
34.3, ,
(. 34.4).

VERSION 5.0
Copyright
Max Schlee
Loading modules: 55%
. 34.4.

34.3 .
,
show ( ) . QLabel ,
. loadModules () ,
,
. QTime (. 37) ,
i 40 .
showMessage ( ) ,
, (. . 7.1), (. . 17.1).
finish!) .
488 V.

, .
, ,
.

34.3. main.cpp

#include <QtWidgets>

//
void loadModules(QSplashScreen* psplash)
{
QTime time;
time.start();

for (int i = 0; i < 100; ) {


if (time.elapsedO > 40) {
time.start();
++i;
}

psplash->showMessage("Loading modules: "


+ QString: inumber(i) + "%",
Qt::AlignHCenter | Qt::AlignBottom,
Qt::black
);
qApp->processEvents();
}
}

//
int main (int argc, char** argv)
{
QApplication app(argc, argv);
QSplashScreen splash(QPixmap(":/splash.png"));

splash.show();

QLabel lbl("<Hl><CENTER>My Application<BR>"


"Is Ready!</CENTERX/Hl>"

loadModules(ssplash);

splash.finish(&lbl);

lbl.resize(250, 250);
lbl.show();

return app.exec();
34. , SDI- MDI- 489

SDI- MDI-
, . SDI
(Single Document Interface, ), MDI (Multiple
Document Interface, ). SDI-
, ,
. MDI-
( QMdiArea), ,
.

SDI-
SDI- (Notepad)
Windows. , 34.4-34.9,
(. 34.5).

. 34.5. SDI-

Docwindow, QTextEdit,
( 34.4). m_strFileName,
. changewindowTitle ( )
, . slotLoadO,
slotsave ( ) slotSaveAs ( ) .

34.4. DocWindow.h

#pragma once

#include <QTextEdit>

/ / ================================
class DocWindow: public QTextEdit {
Q_OBJECT
private:
QString m_strFileName;

public:
Docwindow(QWidget* pwgt =0);
490 V.

signals:
void changeWindowTitie(const QStrings);

public slots:
void slotLoad ();
void slotSave ();
void slotSaveAs();
};

, 34.5, .

34.5. DocWindow.cpp. DocWindow

DocWindow::DocWindow(QWidget* pwgt/*=0*/) : QTextEdit(pwgt )


{
}

slotLoad ( ) , 34.6,
QFileDialog::getOpenFileName () ,
. , ,
Cancel (), .
QString::isEmpty(). getOpenFileName ( )
, QFile,
. QiODevice::Readonly QFile::() ,
.
stream, .
QTextStream::readAll (),
QString.
setPlainText () . close ,
changewindowTitle () ,
DocWindow ,
.

34.6. DocWindow.cpp. slotLoad ()

void DocWindow::slotLoad()
{
QString str = QFileDialog::getOpenFileName();
if (str.isEmpty()) {
return;
}

QFile file(str);
if (file.open(QiODevice::Readonly)) {
QTextStream stream(&file);
setPlainText(stream.readAll());
file.close();

m_strFileName = str;
emit changewindowTitle(m_strFileName);
34. , SDI- MDI- 491

34.7 slotSaveAsO
QFileDialog::getSaveFileName ( ) .
Cancel (), ,
m strFileName , ,
slotSave().

34.7. DocWindow.cpp. slotSaveAs()

void DocWindow::slotSaveAs()
{
QString str = QFileDialog::getSaveFileName(0, m_strFileName);
if (!str.isEmpty()) {
m_strFileName = str;
slotSave();

, ,
, . ,
.
QFile ( 34.8).
(), QiODevice::WriteOnly (,
, ). ,
, , .
, ,
, toPlainText ( ) .
QFile::close ()
. ,
, DocWindow.

34.8. DocWindow.cpp. slotSave()

void DocWindow::slotSave()
{
if (m_strFileName.isEmpty()) {
slotSaveAs();
return;
}

QFile file(m_strFileName);
if (file.open(QiODevice::WriteOnly)) {
QTextStream(sfile) toPlainText();
file.close();
emit changeWindowTitie(m_strFileName);

SDiProgram ( 34.9) QMainwindow.


: File () pmnuFile, Help (-
492 V.

) pmnuHelp
pdoc. addActionO
. ,
, ,
. Open... (...)
slotLoad (), Save () slotSave ( ) , Save As... (
...) slotSaveAs () . DocWindow.
About ( ) slotAbouto,
SDiProgram. menuBar () ,
addMenu ( ) File () Help (
). setCentralwidget
, .

changeWindowTitle () , ,
slotChangeWindowTitle () . showMessage ( ) , ,
Ready , (
2 ).

34.9. SDIProgram.h

#pragma once

#include <QtWidgets>
# include "DocWindow.h"
# include "SDIProgram.h"

//
class SDiProgram : public QMainWindow {
Q_OBJECT
public:
SDiProgram (QWidget* pwgt = 0) : QMainWindow(pwgt)
{
QMenu* pmnuFile = new QMenu("&File");
QMenu* pmnuHelp = new QMenu("&Help");
DocWindow* pdoc = new DocWindow;

pmnuFile->addAction("&Open...",
pdoc,
SLOT (slotLoad ( ) ),
QKeySequence ("CTRL+O")
);
pmnuFile->addAction("&Save",
pdoc,
SLOT(slotSave () ),
QKeySequence ("CTRL+S")
);
pmnuFile->addAction ( "S&ave As..
pdoc,
SLOT (slotSaveAs () )
);
34. , SDI- MDI- 493

pmnuFile->addSeparator();
pmnuFile->addAction("&Quit",
qApp,
SLOT(quit()),
QKeySequence("CTRL+Q")
);
pmnuHelp->addAction("&About",
this,
SLOT(slotAbout()),
Qt::Key_Fl
);

menuBar()->addMenu(pmnuFile);
menuBar()->addMenu(pmnuHelp);

setCentralWidget(pdoc);
connect(pdoc,
SIGNAL(changeWindowTitle(const QStrings)),
SLOT(slotChangeWindowTitle(const QStrings))
);

statusBar()->showMessage("Ready", 2000);
}

public slots:
void slotAbout()
{
QMessageBox::about(this, "Application", "SDI Example");
}

void slotChangeWindowTitle(const QStrings str)


{
setWindowTitle(str);

};

MDI-
MDI-
. ,
.
. ,
.
, (. 34.6),
QMdiArea.
.
tileSubwindows () cascadeSubwindows ( ) , .
QMdiArea: isubwindowList () ,
QMdiSubwindow.
494 V.

QMainWindow

. 34.6. Dl-

( 34.10-34.20), . 34.7,
, MDI-.
Docwindow, SDI- (. 34.4-34.8).

. 34.7. MDI-
34. , SDI- MDI- 495

MDiProgram, 34.10, ,
, Windows (
) m pmnuWindows m_psigMapper.


QAction triggered () .
,
.
QSignaiMapper. . 2.

MDiProgram ,
slotwindows () , : slotLoadO, slotSaveO
slotSaveAs( ) ,
slotNewDoc ( ) ,
slotAbout().

34.10. MDIProgram.h

#pragma once

#include <QMainWindow>

class QMenu;
class QMdiArea;
class QSignaiMapper;
class DocWindow;

,, =========================================
class MDiProgram : public QMainWindow {
Q_OBJECT
private:
QMdiArea* m_pma;
QMenu* m_pmnuWindows;
QSignaiMapper* m_psigMapper;

DocWindow* MDiProgram::createNewDoc();

public:
MDiProgram(QWidget* pwgt = 0);

private slots:
void slotChangeWindowTitle(const QStrings);

private slots:
void slotNewDoc ( );
void slotLoad ( );
void slotSave ( );
void slotSaveAs ( );
void slotAbout ( );
void slotwindows ( );
void slotSetActiveSubWindow(QWidget*);
};
496 V.

MDiProgram ( 34.1 1)
, pactNew, pactOpen
pactSave . triggered ()
MDiProgram. addActionO
.
File | Quit ( | )
closeAllwindows( ) , .
MDI- QMdiArea.
,
setHorizontalScrollBarPolicy() setVerticalScrollBarPolicy(),
Qt::ScrollBarAsNeeded
, .
setCentralwidget ( ).
( m_psigMapper)
mapped () slotSetActiveSubwindowO,
MDiProgram. ,
slotSetActiveSubwindowO.
(. 34.20).
showMessage(), ,
Ready 3 .

34.11. MDIProgram.cpp. MDiProgram

MDiProgram::MDiProgram(QWidget* pwgt/*=0*/) : QMainWindow(pwgt)


{
QAction* pactNew = new QAction("New File", 0);
pactNew->setText("&New");
pactNew->setShortcut(QKeySequence("CTRL+N"));
pactNew->setToolTip("New Document");
pactNew->setStatusTip("Create a new file");
pactNew->setWhatsThis("Create a new file");
pactNew->setIcon(QPixmap(":/filenew.png"));
connect(pactNew, SIGNAL(triggered()), SLOT(slotNewDoc()));

QAction* pactOpen = new QAction("Open File", 0);


pactOpen->setText("&Open...");
pactOpen->setShortcut(QKeySequence("CTRL+O"));
pactOpen->setToolTip("Open Document" );
pactOpen->setStatusTip("Open an existing file");
pactOpen->setWhatsThis("Open an existing file");
pactOpen->setIcon(QPixmap(":/fileopen.png"));
connect(pactOpen, SIGNAL(triggered()), SLOT(slotLoad()));

QAction* pactSave = new QAction("Save File", 0);


pactSave->setText("&Save");
pactSave->setShortcut(QKeySequence("CTRL+S"));
pactSave->setToolTip("Save Document" );
pactSave->setStatusTip("Save the file to disk");
34. , SDI- MDI- 497

pactSave->setWhatsThis("Save the file to disk");


pactSave->setIcon(QPixmap(":/filesave.png"));
connect(pactSave, SIGNAL(triggered()), SLOT(slotSave()));

QToolBar* ptbFile = new QToolBar("File Operations");


ptbFile->addAction(pactNew);
ptbFile->addAction(pactOpen);
ptbFile->addAction(pactSave);
addToolBar(Qt::TopToolBarArea, ptbFile);

QMenu* pmnuFile = new QMenu("&File");


pmnuFile->addAction(pactNew);
pmnuFile->addAction(pactOpen);
pmnuFile->addAction(pactSave);
pmnuFile->addAction("Save &As...", this, SLOT(slotSaveAs()));
pmnuFile->addSeparator();
pmnuFile->addAction("&Quit",
qApp,
SLOT(closeAllWindows()),
QKeySequence("CTRL+Q")
);
menuBar()->addMenu(pmnuFile);

m_pmnuWindows = new QMenu("&Windows");


menuBar()->addMenu(m_pmnuWindows);
connect(m_pmnuWindows, SIGNAL(aboutToShow()), SLOT(slotWindows()));
menuBar()->addSeparator();

QMenu* pmnuHelp = new QMenu("&Help");


pmnuHelp->addAction("&About", this, SLOT(slotAbout()), Qt::Key_Fl);
menuBar()->addMenu(pmnuHelp);

m_pma = new QMdiArea;


m_pma->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
m_pma->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);

setCentralWidget(m_pma);

m_psigMapper = new QSignalMapper(this);


connect(m_psigMapper,
SIGNAL(mapped(QWidget*)),
this,
SLOT(slotSetActiveSubWindow(QWidget*))
);

statusBar()->showMessage("Ready", 3000);
}

slotNewDocO, 34.12,
.
498 V.

34.12. MDIProgram.cpp. slotNewDocO

void MDIProgram::slotNewDoc()
{
createNewDoc()->show();
}

34.13 createNewDoc ( ) DocWindow,


addSubwindow ( ) .
setAttribute ( ) Qt : :WA_DeleteOnClose, ,
.
setwindowTitle () .
setwindowiconO .
, , ,
changeWindowTitle ( ) slotChangeWindowTitle().

34.13. MDIProgram.cpp. createNewDoc()

DocWindow* MDIProgram::createNewDoc()
{
DocWindow* pdoc = new DocWindow;
m_pma->addSubWindow(pdoc);
pdoc->setAttribute(Qt::WA_DeleteOnClose);
pdoc->setWindowTitle("Unnamed Document");
pdoc->setWindowIcon(QPixmap(":/filenew.png"));
connect(pdoc,
SIGNAL(changeWindowTitle(const QStrings)),
SLOT(slotChangeWindowTitle(const QStrings))

return pdoc;
}

slotChangeWindowTitle () private .
DocWindow,
setwindowTitle () ,
( 34.14).

34.14. MDIProgram.cpp. slotChangeWindowTitle()

void MDIProgram::slotChangeWindowTitle(const QStrings str)


{
qobject_cast<DocWindow*>(sender())->setWindowTitle(str);
}

slotLoadO createNewDoc ,
, ,
( 34.15).
34. , SDI- MDI- 499

34.15. MDIProgram.cpp. slotLoadO

void MDIProgram::slotLoad()
{
DocWindow* pdoc = createNewDoc();
pdoc->slotLoad();
pdoc->show();
}

siotSave ()
, , DocWindow ,
( 34.16).

34.16. MDIProgram.cpp. slotSaveQ

void MDIProgram::slotSave()
{
DocWindow* pdoc = qobject_cast<DocWindow*>(m_pma->activeSubWindow());
if (pdoc) {
pdoc->slotSave();
}
}

slotSaveAsO slotSaveO (. 34.16),


slotSaveAs () ( 34.17).

34.17. MDIProgram.cpp. slotSaveAs()

void MDIProgram::slotSaveAs()
{
DocWindow* pdoc = qobject_cast<DocWindow*>(m_pma->activeSubWindow());
if (pdoc) {
pdoc->slotSaveAs();

slotAbout ( ) (
34.18).

34.18. MDIProgram.cpp. slotAboutO

void MDIProgram::slotAbout()
{
QMessageBox::about(this, "Application", "MDI Example");
}

MDI- SDI
Windows (),
,
. ,
clear () ( 34.19).
500 V.

Windows () Cascade () Tile


(). (
subwindowList ( )), setEnabledO
. for
. setCheckable ( ) true
, ,
. ,
, setChecked( ) .
, triggered ( ) ( pact) ( )
m psigMapper. ,
mapped () (. 34.1 1)
, at ( ) , setMapping ().

34.19. MDIProgram.cpp. slotwindows ()

void MDIProgram::slotwindows ()
{
m_pmnuWindows->clear ( );

QAction* pact = m_pmnuW i ndows->addAct ion("&Cascade",


m_pma,
SLOT(cascadeSubWindows () )
);

pact->setEnabled ( !m_pma->subWindowList ().isEmpty( ) );

pact = m_pmnuWindows->addAction ("&Tile",


m_pma,
SLOT (tileSubWindows( ) )
);
pact->setEnabled ( !m_pma-> subwindowList ().isEmpty( ) );

m_pmnuWindows->addSeparator();

QList<QMdiSubWindow*> listDoc = m_pma->subWindowList ();


for (int i = 0; i < listDoc.size(); ++i) {
pact = m_pmnuWindows->addAction(listDoc.at (i)->windowTitle ( ));
pact->setCheckable(true);
pact->setChecked(m_pma->activeSubWindow ( ) == listDoc.at (i) );
connect (pact, SIGNAL(triggered () ), m_psigMapper, SLOT (map ( ) ));
m_psigMapper->setMapping (pact, listDoc.at (i) );

slot Set Act iveSubwindow() ( 34.20)


. ,
, QMdiSubwindow
set ActiveSubWindow ( ).
34. , SDI- MDI- 501

34.20. MDIProgram.cpp. slotSetActiveSubWindow()

void MDIProgram::slotSetActiveSubWindow(QWidget* pwgt)


{
if (pwgt) {
m_pma->setActiveSubWindow(qobject_cast<QMdiSubWindow*>(pwgt));


. ,
, .

: ,
.
QAction
, , .
, .
: SDI (Single Document Interface,
) MDI (Multiple Document Interface,
). MDI SDI-
, SDI- , MDI-
,
.
QMainwindow ,
, . ,
. QMdiArea
, MDI-.
, ,
, , , . .
,
QSplashScreen. .
35

(Desktop)

,
, .


, ,
. ,
, . ,
.


(Notification area) . Windows
(. 35.1) (Taskbar Notification Area),
(System Tray),
( KDE (. 35.2) GNOME
(. 35.3)), Mac OS X Menu Extras
(. 35.4). .
.

> 9:43
ti % Q 04:13 Pm 1/

. 35.1. Windows . 35.2. KDE/Linux

) PrI Jan 30, 4:10 | t 1 @ Thu 17:11 Q,


. 35.3. GNOME/Linux . 35.4. Mac OS X

,
( ), ,
. , , , Skype ICQ, Windows
.
, ,
.
35. (Desktop) 503

, , ,

.
, ?
QSystemTrayicon.
. . ,
seticonO,
show ( ) . ,
showMessage().

setToolTip()
, ,
, . , ,
,

. setContextMenu().
.
( 35.1-35.7) ,
(. 35.5):
Show/Hide Application Window (/ )
. 35.6 . , ;
Show Message ( ) , . 35.7;
Change Icon ( )
;
Quit ().
, (. 35.8).

Sh w/Hi de Application Wi n d w
Show Message
Changelccn System Tray
Quit
Application Window
larmF- Editor < L3 F 4* 12:22 AM
. 35.5. . 35.6.

For your information


You have selected the "ShowMessage!" option
V C-

. 35.7. . 35.8.

, 35.1, .
,
QApplication::setQuitOnLastwindow ( )
false. Qt , , ,
504 V.

, , ,
.
show().

35.1. main.cpp

#include <QtWidgets>
#include "SystemTray.h"

int main(int argc, char** argv)


{
QApplication app(argc, argv);
SystemTray st;

QApplication::setQuitOnLastWindowClosed(false);

return app.exec();
}
, 35.2,
. QLabel, .
:
QSystemTrayicon ( m_ptrayicon),
;
QMenu ( m ptrayiconMenu),
;
m biconSwitcher,
.
closeEvent(),
.
: slotShowHide ( ) , slotShowMessage ( ) slotChangelcon ( )
.

35.2. SystemTray.h

#pragma once

#include <QLabel>

class QSystemTrayicon;
class QMenu;

/ / ==================================
class SystemTray : public QLabel {
Q_OBJECT
private:
QSystemTrayicon* m_ptrayIcon;
QMenu* m_ptrayIconMenu;
bool m blconSwitcher;
35. (Desktop) 505

protected:
virtual void closeEvent(QCloseEvent*);

public:
SystemTray(QWidget* pwgt = 0);

public slots:
void slotShowHide ();
void slotShowMessage();
void slotChangelcon ();
};

( 35.3) (QAction)
. (QMenu)
.
(QSystemTrayicon), this.
setContextMenu() .
setToolTip() System Tray.
slotChangelcon(),
. , show()
.

35.3. SystemTray..

SystemTray::SystemTray(QWidget* pwgt /*=*/)


: QLabel("<H1application Window</Hl>", pwgt)
, m_bIconSwitcher(false)
{
setWindowTitle("System Tray")

QAction* pactShowHide =
new QAction("&Show/Hide Application Window", this);

connect(pactShowHide, SIGNAL(triggered()),
this, SLOT(slotShowHide())

QAction* pactShowMessage = new QAction("Sshow Message", this);


connect(pactShowMessage, SIGNAL(triggered()),
this, SLOT(slotShowMessage())
);

QAction* pactChangelcon = new QAction O'&Change Icon", this);


connect(pactChangelcon, SIGNAL(triggered()),
this, SLOT(slotChangelcon())
);

QAction* pactQuit = new QAction("&Quit", this);


connect(pactQuit, SIGNAL(triggered()), qApp, SLOT(quit()));

m_ptrayIconMenu = new QMenu(this);


m_ptrayIconMenu->addAction(pactShowHide);
506 V.

m_ptrayIconMenu->addAction(pactShowMessage);
m_ptrayIconMenu->addAction(pactChangelcon);
m_ptrayIconMenu->addAction(pactQuit);

m_ptrayIcon = new QSystemTraylcon(this);


m_ptrayIcon->setContextMenu(m_ptrayIconMenu);
m_ptrayIcon->setToolTip( "System Tray");

slotChangelcon();

m_ptrayIcon->show();
)

, , ,
.
( 35.4). , ,
, hide ( ) , .

35.4. SystemTray.cpp. closeEventO

/*virtual*/void SystemTray::closeEvent(QCloseEvent* pe)


{
if (m_ptrayIcon->isVisible()) {
hide();

siotshowHide ( ) , 35.5, Show/Hide


Application Window.
. , , , .

35.5. SystemTray.cpp. slotShowHideO

void SystemTray::slotShowHideO
{
setvisible(!isVisible());
}

slotshowMessage ( ) Show Message.


showMessage ( ) ( 35.6).
, , ,
,
,
, 3 .

35.6. SystemTray.cpp. slotshowMessage ( )

void SystemTray::slotshowMessage()
{
m_ptrayIcon->showMessage("For your information",
"You have selected the "
35. (Desktop) 507

"V'Show Message!\" option",


QSystemTraylcon::Information,
3000
);
}

slotchangeicon ( ) Change Icon


( 35.7).
m biconSwitcher ,
, : img1.bmp img2.bmp.
seticon().

35.7. SystemTray.cpp. slotchangeicon ( )

void SystemTray: : slotchangeicon ( )


{
m_bIconSwitcher = !m_bIconSwitcher;
QString strPixmapName = m_bIconSwitcher ? " : /images/imgl .bmp"
: " : / image s / img2 . bmp ";
m_ptrayIcon->setIcon (QPixmap (strPixmapName) ) ;
}


QDesktopwidget .
,
,
. , ,
.
desktopO, QApplication. ,
, :
1. , QApplication: : desktop!) .
2. width ( ) height ( ) .
3.
(width ( ) height ( ) ).
4. move ( ) .
:
pwgt->move ( (QApplication: : desktop ->width ( ) pwgt->width ( ) ) / 2,
(QApplication: : desktop () ->height ( ) pwgt->height ( ) ) / 2
);

,
, ,
( , ,
, ,
):
508 V.

numScreens ( ) ;
primaryScreen ( ) ,
;
isvirtualDesktop ( ) .
,

;
screenNumber ( )
( QPoint)
, . :
int nScreen = desktopWidget->screenNumber(QPoint(320, 115));


, QDesktopWidget : :screenGeometry ( )
width () height() .
:
QDesktopWidget* pwgt = QApplication::desktop();
for (int i = 0; i < pwgt->numScreens(); ++i) {
qDebugO "Screen:" i;
qDebugO "width:" pwgt->screenGeometry(i).width();
qDebugO "height:" pwgt->screenGeometry(i).height();
}

, QDesktopWidget
resized!) ,
screenCountChangedt ).
.
( 35.8-35.11),
Capture Screen ( )
(. 35.9).
( 35.8) 35.9-
35.1 1 Grabwidget, .

35.8. main.cpp

#include <QtWidgets>
#include "Grabwidget.h"

int main(int argc, char** argv)


{
QApplication app(argc, argv);
Grabwidget wgt;

wgt.show();

return app.exec( );
35. (Desktop) 509

. 35.9. ,

Grabwidget ( 35.9)
(m_pibi),
. slotGrabScreen{),
.

35.9. GrabWidget.h

#pragma once

#include <QWidget>

class QLabel;

/ / ================================
class Grabwidget : public QWidget {
Q_OBJECT
private:
QLabel* m_plbl;

public:
Grabwidget(QWidget* pwgt = 0);
510 V.

public slots:
void slotGrabScreen();
};

, 35.10, Capture
Screen ( ) clicked ()
slotGrabScreen ( ) .
pvbxbayout.

35.10. GrabWidget.cpp.

Grabwidget::GrabWidget(QWidget* pwgt /*=0*/) : QWidget(pwgt)


{
resize(640, 480);

m_plbl = new QLabel;

QPushButton* pcmd = new QPushButton("Capture Screen");


connect(pcmd, SIGNAL(clicked()), SLOT(slotGrabScreen()));

//Layout setup
QVBoxLayout* pvbxLayout = new QVBoxLayout;
pvbxLayout->addWidget(pcmd);
pvbxLayout->addWidget(m_plbl);
setLayout(pvbxLayout);
)

35.11 , , ,
.
, desktop ( ) . QPixmap

, grabwindow ( )
, , , winid ( ) .

grabwindow ( ) ,
. ,
. screen ( ) ,
,
, , ,
. ,
.


,
QDesktopWidget::numScreens().


( scaled( ) ),
setPixmap().
35. (Desktop) 511

35.11. GrabWidget.cpp. slotGrabScreen()

void GrabWidget::slotGrabScreen()
{
QDesktopWidget* pwgt = QApplication::desktop();
QPixmap pic = QPixmap::grabWindow(pwgt->screen( )->winld());

m_plbl->setPixmap(pic.scaled(m_plbl->size()));
}


QDesktopServices.
, , , ,
, , , . .
storageLocation ( ) , : QDesktopServices: :
MoviesLocation.

Web-. Web-
, , :
bool bRes = QDesktopServices::openUrl(QUrl ("http://www.bhv.ru"));
qDebugO "Result:" bRes;
. ,
:
QDesktopServices::openUrl(QUrl::fromLocalFile(":\\myfile.txt"));

( Windows )
, , ,
.
QSystemTraylcon.
QDesktopWidget.
.
QDesktopServices Web-
.
VI

Qt


, . ,
.
, .

36. , /
37. ,
38.
39.
40. XML
41.
42.
43. Qt API
44. Qt Designer.
45.
46. WebKit
47. Qt Creator
48. Qt 4 Qt 5
36

,
/

, ,
.

, . (
, Windows) ,
, Qt
, :
QDir ;
QFile ;
QFileinfo ;
QiODevice /;

QBuffer .

/. QiODevice
QiODevice , /,
/,
.
. Qt
, QiODevice (. 36.1):
QFile ;

QBuffer ,
QByteArray, ;

QAbstractSocket
(. 39);
QProcess ,
(. 38)
, QiODevice.
516 VI. Qt

. 36.1. /
QObject

QiODevice

QAbsf ractStocket I

,
QiODevice:
J QTcpSocket

J QS si Socket
J

QiODevice::NotOpen ( [ QUdpSockei
open ());
QFile
QiODevice::Readonly
; [ QTemporaryFile
QiODevice::WriteOnly
; [ QBuffer
QiODevice:: ReadWrite | QProcess
( , Readonly | writeOnly);
QiODevice::Append ;
QiODevice: Unbuffered
;
QiODevice::Text
. Windows "\\", MacOS X
Unix "\";
QiODevice::Truncate , ,
.
,
, openMode ( ).
read ( ) write ( ) .
readAll(),
QByteArray. readLine ( ) getChar ( )
.
QiODevice : seek ( ) .
pos . ,
. ,
, . ,
size , .
QFile, QBuffer QTemporaryFile.
/, Qt
, QiODevice
readData ( ) writeData ( ) .
open( ), close ( ) atEnd ( ).
QiODevice, ,
, ,
. ,
:
36. , / 517

void print(QIODevice* pdev)


{
char ch;
QString str;

pdev->open(QIODevice::Readonly);
for (; !pdev->atEnd();) {
pdev->getChar(&ch);
str += ch;

pdev->close();
qDebugO str;

QIODevice ,
/. ,
, , , .
, ,
isReadable ( ) isWriteable( ) .

. QFile
QFile QIODevice (. . 36.1).
: , , . ,
, .
, setName ( ) . :
QFile file;
file.setName("file.dat");

, .
QIODevice::isOpen(), true, ,
false. , close ( ) .
.
, QFile:: flush ( ) .
, , QFile::exists .
, .
, true, false.
QFile: : exists ,
, fileNameO. QIODevice: : read
QIODevice: : write .
:
QFile filel("filel.dat");
QFile file2("file2.dat ");
if (file2.exists()) {
// . ?

if (!filel.open(QIODevice::Readonly)) {
qDebugO << " ";
)
518 VI. Qt

if (!file2.open(QIODevice::WriteOnly)) {
qDebugO " ";
}
char [1024];
while(!filel.atEnd()) {
int nBlocksize = filel.read(a, sizeof(a));
file2.write(a, nBlocksize);
}
filel.close();
file2.close();
,
QIODevice::write () QIODevice::readAll () .
QByteArray, :

QFile filel("filel.dat");
QFile file2("file2.dat");

if (file2.exists()) {
// . ?
}
if (!filel.open(QIODevice::Readonly)) {
qDebug() " ";
}
if (!file2.open(QIODevice::WriteOnly)) {
qDebugO " ";
}
QByteArray = filel.readAll();
file2.write(a);

filel.close();
file2.close();



, ,
, .
,
. qCompressO
quncompress , QByteArray.
QByteArray
QByteArray.

.
QFile remove()
, .

QBuffer
QBuffer QIODevice (. . 36.1)
(memory mapped files).
:
36. , / 519

open ( ) close ( ) . write ( ) read ( )


. ,
, :
QByteArray arr;
QBuffer buffer (&arr) ;
buffer .open (QIODevice: :WriteOnly) ;
QDataStream out (sbuffer) ;
out QString ( "Message" ) ;

, QByteArray.
buffer ( )
QByteArray, setBuffer ( ) QByteArray
.
data () buffer (), setDataO setBuffer ()
, QByteArray,
.
QBuffer . ,
QBuffer, , ,
.

QTemporaryFile
. ,
,
- .
QTemporaryFile .
, ,
, .
,
QDir: :tempPath().
.

. QDir
. Windows
, : C:\Windows\System. UNIX /,
: /usr/bin. ,
.
Qt QDir.
, :
QDir : : current ( ) ;
QDir : :root ( ) ;
QDir : : drives ( ) QFileinfo,
( Windows :\, D:\ . .);
QDir : : home ( ) .
520 VI. Qt


QDir ,
. ,
QApplication: : applicationDirPath ( ) , QApplication: :
applicationFilePath ( ) , .

exists ().
, cd(),
. ..
, cdup ( ) cd ( " " ) cdup ( ) .
, .

makeAbsolute ( ) .

mkdir ( ) .
true, false.
,
rename ( ) . ,
. , true, false.
rmdir(), ,
true, false.


QDir .
,
. entryList ( ) entryinfoList ( ) .
(QStringList),
(QFileinfoList). ,
, count ( ) .
( 36.1-36.4), . 36.2,
, Directory ().

. 36.2.
36. , / 521

.
Mask () . ,
C++ Mask () *.
*.h. Find ()
.
.
FileFinder, 36.1,
( m ptxtDir, m ptxtMask
m ptxtResuit). ,
QDir::absolutePath ( ) , , ,
, QDir::current () .
, .
( pcmdFind
pcmdDir), slotFindO slotBrowseO .
setBuddy ( )
.
QGridLayout (. ).

36.1. FileFinder.cpp. FileFinder

FileFinder::FileFinder(QWidget* pwgt/*= 0*/) : QWidget(pwgt)


{
m_ptxtDir = new QLineEdit(QDir::current().absolutePath());
m_ptxtMask = new QLineEdit("*.cpp *.h");
m_ptxtResult = new QTextEdit;

QLabel* plblDir = new QLabel("SDirectory");


QLabel* plblMask = new QLabel("SMask");
QPushButton* pcmdDir = new QPushButton(QPixmap(":/fileopen.png"),
QPushButton* pcmdFind = new QPushButton("SFind");

connect(pcmdDir, SIGNAL(clicked()), SLOT(slotBrowse()));


connect(pcmdFind, SIGNAL(clicked()), SLOT(slotFind()));

plblDir->setBuddy(m_ptxtDir);
plblMask->setBuddy(m_ptxtMask);

//Layout setup
QGridLayout* pgrdLayout = new QGridLayout;
pgrdLayout->setMargin(5);
pgrdLayout->setSpacing(15);
pgrdLayout->addWidget(plblDir, 0, 0);
pgrdLayout->addWidget(plblMask, 1, 0);
pgrdLayout->addWidget(m_ptxtDir, 0, 1);
pgrdLayout->addWidget(m_ptxtMask, 1, 1);
pgrdLayout->addWidget(pcmdDir, 0, 2);
pgrdLayout->addWidget(pcmdFind, 1, 2);
pgrdLayout->addWidget(m_ptxtResult, 2, 0, 1, 3);
setLayout(pgrdLayout);
522 VI. Qt

36.2 slotBrowse () ,
.
Directory () setText ( ) .

36.2. FileFinder.cpp. slotBrowse()

void FileFinder ::slotBrowse ( )


{
QString str = QFileDialog: :getExistingDirectory (0,
"Select a Directory",
m_ptxtDir->text ( )

if ( ! str .isEmpty ( ) ) {
m_ptxtDir->setText (str) ;
}

slotFindO , start ()
( 36.3).

36.3. FileFinder.cpp. slotFindO

void FileFinder: :slotFindO


{
start (QDir (m_ptxtDir->text ( ) ) );
}

start () ( 36.4).
,
,
.
QApplication: :processEvent { )
. start () listFiles
, . .
,
. ,
QString: : split () . ( QDir:: Files) ,
.
append ( ) .
entryList () QDir: :Dirs
. , " . " " . . start ( ) .

36.4. FileFinder.cpp. start()

void FileFinder ::start (const QDir& dir)


{
QApplication: :processEvents ( ) ;
36. , / 523

QStringList listFiles =
dir.entryList (m_ptxtMask->text () .split (" ") , QDir :: Files) ;

foreach (QString file, listFiles) {


m_ptxtResult->append (dir .absoluteFilePath (file) ) ;
}

QStringList listDir = dir .entryList (QDir :: Dirs) ;


foreach (QString subdir, listDir) {
if (subdir == " . " || subdir {
continue;
}
start (QDir (dir .absoluteFilePath (subdir) ) ) ;


36.4 QDir: :NoDotAndDotDot
. ..
" " " .

entryList () .
setFilter().
setsorting () .
, :
.
dir setFilter (QDir: : Files I QDir: : Hidden) ;
.
dir setSorting (QDir : :Size) ;
QStringList content = dir .entryList () ;

. QFilelnfo
QFilelnfo :
, , , . .
QFile.

?
, , ,
. isFileO isDir().
, isFileO true, false.
, isDir ( ) true, false. ,
QFilelnfo isSymLinkO, true,
( symbolic link UNIX, Windows
(shortcut)).

UNIX
. in -s.
524 VI. Qt



,
filePathf).
absoluteFilePath ( ) ,
fileNameO,
. , baseName ( ) .
compieteSuffix ( ) .


, .
QFilelnfo createdO, lastModifiedO lastReadO
. QDateTime (. 38),
toString ( ) . :
//
filelnfo.created().toString();

//
filelnfo.lastModified().toString();

//
filelnfo.lastRead().toString();


, .
QFilelnfo :
isReadabie ( ) true,
;
iswriteable ( ) true,
;
true, ;
isHidden ( )
isExecutable ( ) true, .
UNIX , DOS
Windows, .


size QFilelnfo .
, ,
. ,
, ,
G, .
, ( ,
):
QString fileSize(qint64 nSize)
{
int i = 0;
36. , / 525

for (; nSize > 1023; nSize /= 1024, ++i) {


if(i >= 4) {
break;

return QString().setNum(nSize) + "BKMGT"[i];


}


,
. ,
.
,
.
,
.
QFileSystemWatcher.
addPathO ,
,
removePath ( ) . fileChanged( ) ,
directoryChangedO . ,
.
.
( 36.5-36.7),

(. 36.3).

1 *1 File System Watcher [ ~|


Watchinq files:c:\WINDOW5\0, Hog
Watching dirs:c:\WINDOWS
F ile changed :c:\WINDOWS\0 log .
F ile changed ; c:\WINDOW5\0,log . 36.3. ,
File changed:c:\WINDOW5\0 log
Directory changed:c:\WINDOWS
.

(. 36.5)
QTextEdit
slotDirectory ( ) slotFileChaged().

36.5. Viewer.h

#pragma once

#include <QTextEdit>
526 VI. Qt

/ / =====================================
class Viewer : public QTextEdit {
Q_OBJECT
public:
Viewer(QWidget* pwgt = 0);

private slots:
void slotDirectoryChanged(const QStrings);
void slotFileChanged (const QStrings);
};

( 36.6) .
append ( )
slotDirectoryChanged ( ) slotFileChanged().

36.6. Viewer.cpp

#include "Viewer.h"

//
Viewer::Viewer(QWidget* pwgt /*=0*/) : QTextEdit(pwgt)
{
setWindowTitle("File System Watcher");
}

//
void Viewer::slotDirectoryChanged(const QStrings str)
{
append("Directory changed:" + str);
}

//
void Viewer::slotFileChanged(const QStrings str)
{
append("File changed:" + str);
}

36.7 (watcher)
(viewer). () ,
( arguments ).
, .
QFileSystemWatcher::addPaths().
,
, . ,
( QFileSystemWatcher::files ()) ( QFileSystemWatcher::
directories ). QFileSystemWatcher::
directoryChangedO QFileSystemWatcher::fileChanged( ) slotDirectoryChanged()
slotFileChanged ( ) .
36. , / 527

36.7. main.cpp

#include <QtWidgets>
#include "Viewer.h"

int main(int argc, char** argv)


{
QApplication app(argc, argv);
QFileSystemWatcher watcher;
Viewer viewer;

QStringList args = app.arguments();


args.removeFirst();

watcher.addPaths(args);

viewer.append("Watching files:" + watcher.files().join(";"));


viewer.append("Watching dirs:" + watcher.directories().join(";"));
viewer.show();

QObject::connect(&watcher, SIGNAL(directoryChanged(const QStrings)),


Sviewer, SLOT(slotDirectoryChanged(const QString&))
);
QObject::connect(Swatcher, SIGNAL(fileChanged(const QStrings)),
Sviewer, SLOT(slotFileChanged(const QStrings))
);

return app.exec();
}

/

.
. , ,
QTextStream, QDataStream.
QTextStream QDataStream ,
/ C++ (iostream), ,
QiODevice.
, QiODevice.
, .

QTextStream
QTextStream .
, ,
QiODevice, char, QChar, char*, QString, QByteArray, short, int, long,
float double. , ,
528 VI. Qt

. , QTextstream::
setRealNumberPrecision ( ) .
Unicode.
, QFile
QTextstream::readLine ( ) . :
QFile file("file.txt");
if ( file.open(QIODevi::Readonly) ) {
QTextstream stream(&file);
QString str;
while ( ! stream.atEnd() ) {
str = stream.readLine ();
qDebugO str;
}
if ( stream.status () != QTextstream::Ok) {
qDebugO " ";
}
file.close ();
}

QTextstream::readAll() .
:
QFile file("myfile.txt");
if ( file.open(QIODevice::Readonly)) {
QTextstream stream(&file );
QString str = stream.readAll();
file.close ();
}

, QFile
.
. :
QFile file("file.txt");
QString str = "This is a test";
if (file.open(QIODevice::WriteOnly) ) {
QTextstream stream(sfile);
stream str.toUpper (); // THIS IS A TEST
file.close ();

if ( stream.status () != QTextstream::0k) {
qDebugO " ";
}
}

QTextstream ,
.
QDataStream.
36. , / 529

QDataStream
QDataStream , , ,

. -
(. 39). , QDataStream,
Qt .
,
, Qt,
setversion ( ) , .
Qt_5_3.
, , :
Variant.
QByteArray, QFont, Qlmage, QMap, QPixmap, QString, QValueList
(QPointF), ,
(Qlmage):
QFile file("file.bin");
if(file.open(QIODevice::WriteOnly)) {
QDataStream stream(&file);
stream.setversion(QDataStream::Qt_5_3);
stream QPointF(30, 30) Qlmage("image.png");

if (stream.status( ) != QDataStream::Ok) {
qDebugO " ";

file.close();

:
QPointF pt;
Qlmage img;
QFile file("file.bin");
if(file.open(QIODevice::ReadOnly)) {
QDataStream stream(sfile);
stream.setversion(QDataStream::Qt_5_3);
stream pt img;

if (stream.status() != QDataStream::0k) {
qDebugO " ";
}
)
file.close();

Qt QIODevice,
/. , QIODevice,
. QFile QBuffer .
530 VI. Qt

QFile , , ,
, .
QBuffer .
, ,
.
QDir .
,
, .
QFileinfo
.
Qt
QFileSystemWatcher.
Qt ,
: QDataStream QTextStream .
C++.
, .
, QiODevice, QFile
, , QBuffer.
37

, .
.


,
.



,
. Qt
: QDate, QTime QDateTime, QDate,
QTime QDateTime.

QDate
QDate
. QDate
. , , . ,
, 25 2014 :
QDate date (2014, 10, 25);

setDate ( ) .
:
QDate date;
date. setDate (2014, 10, 25);

, , ,
:
year ( ) 1752 8000;
month 1 12 (
);
day ( ) 1 31.
daysinMonthO ,
daysinYear ( ) .
532 VI. Qt

dayOfWeek ( ) .
dayOfYear ( ) . ,
weekNumber().
tostring ( ) ,
, . 37.1.

37.1. DateFormat Qt

TextDate 0x0000 Qt ( )
ISODate 0x0001 ISO 8601 (YYYY-MM-DD)
SystemLocaleDate 0x0002 ,

LocaleDate 0x0003 , ,
QLocale::setDefault().
, SystemLocaleDate

, ,
tostring ( ) -, . :
QDate date(2014, 7, 3);
QString str;
str = date.toString("d.M.yy"); //str = "3.7.14"
str = date.toString("dd/MM/yy"); //str = "03/07/14"
str = date.toString("yyyy..ddd"); //str = "2014.."
str = date.toString("yyyy.MMMM.dddd");//str = "2014.."

addDays ( ) ,
. addMonths ( ) addYears ( ) ,
, . :
QDate date(2014, 1, 3);
QDate date2 = date.addDays(-7);
QString str = date2.toString("dd/MM/yy"); //str = "27/06/14"

QDate fromstring ( ) ,
QDate.
,
. 37.1 .
.
currentDate(), QDate.
daysTo ( ) .
:

QDate dateToday = QDate::currentDate();


QDate dateNewYear(dateToday.year(), 12, 31);
qDebug() " "
dateToday.daysTo(dateNewYear)
" ";
37. , 533

, QDate
==, !=, <, <=, > >=. :
QDate datel(2014, 1, 3);
QDate date2(2014, 1, 5);
bool b = (datel == date2); //b = false

QTime
,
, ,
. .
Qt QTime.
, ==, ! =, <, <=, >
>=. .
QTime . ,
, , .
, . :
QTime time(20, 4);


setHMS(). :
QTime time;
time.setHMS (20, 4, 23, 3);

, , ,
, QTime :
hour ( ) 0 23;
minute ( ) 0 59;
second ( ) 0 59;
msec ( ) 0 999.
QTime toString ( )
. , , ,
. 37.1, . :
QTime time(20, 4, 23, 3);
QString str;
str = time.toString("hh:mm:ss.zzz"); //str = 20:04:23.003"
str = time.toString("h:m:s ap"); //str = "8:4:23 pm"

fromstring ( )
QTime. ,
. ,
. 37.1, .
, ( )
. addSecs() addMSecs().
QTime currentTime ( ) .
534 VI. Qt

start () , ,
, elapsed (). ,
, ,
,
. test():
QTime time;
time.start();
test();
qDebug() " test() "
time.elapsed()
" "
endl;
QTime 24- ,
.
QDateTime.

QDateTime
QDateTime . date()
(QDate), time() (QTime).
toStringO .
, . 37.1,
.


. ,
QTime
:
QTime time;
time.start();
for(;time.elapsed() < 1000;) {
}
function();
.
. -
, , , ,
, .
, processEvents ()
QApplication, ,
. :
QTime time;
time.start();
for(;time.elapsed() < 1000;) {
qApp->processEvents();
}
37. , 535


,
, ,
.
.
, .
, .
,
, .
(firing interval).
, .
, , , ,
, 1 .
,
(. 37.5).
, , ,
, , 24 .
.
. ,

(. 38) ,
.
, .
, ,
.
(. 38)
, (event loop).
QThread: : () .


, QObject,
. QObject: :startTimer () .
. startTimer ( ) ,
, .
QTimerEvent,
timerEvent(). QTimerEvent: :timerld () QTimerEvent,
, .
, QObject: :killTimer .
( 37.1 37.2), . 37.1, ,
.

. 37.1.
536 VI. Qt

main () ( 37.1) BlinkLabel,


HTML.

37.1. main.cpp. man()

int main (int argc, char** argv)


{
QApplication app (argc, argv) ;
BlinkLabel lbl("<FONT COLOR = RED><CENTER>Blink</CENTERX/FONT>") ;

.
lbl show ( ) ;

return app . exec ( ) ;


}

BlinkLabel, 37.2, m bBlink,


, m_strText, .
BlinkLabel ninterval.
200 . startTimer ( )
. QTimerEvent,
timerEvent () , m_bBlink
. setText ( )
:
false ;
true .

37.2. main.cpp. BlinkLabel

class BlinkLabel : public QLabel {


private :
bool m_bBlink;
QString m_strText;

protected:
virtual void timerEvent (QTimerEvent*)
{
m_bBlink = !m_bBlink;
setText (m_bBl ink ? m_strText : "" );
}

public:
BlinkLabel (const QSt rings strText,
int ninterval = 200,
QWidget* pwgt = 0
)
: QLabel (strText, pwgt)
, m_bBl ink (true)
, m_strText (strText)
37. , 537

{
startTimer(nlnterval);
}

QTimer
QTimer , ,
QObject.
, QObject.
, .
,
, , .
Qt QTimer,
QObject. ,
QTimer, start ( ) .
.
QTimer singleShotO
( singleshot).
QTimer. -
, , .
. ,
, - 5
( 37.3).

37.3.

int main(int argc, char** argv)

QApplication app(argc, argv);


MyProgram myProgram;

QTimer::singleShot(5 * 60 * 1000, &app, SLOT(quit()));

myProgram.show();

return app.exec();

timeout (),
, . setinterval()
. ,
,
. isActive ( ) ,
. stop ( ) .
, .
, -
, , , ,
538 VI. Qt

,
. delay ,
, (
37.4).

37.4.

void delay(int n)
{
QEventLoop loop;
QTimer::singleShot(n, sloop, SLOT(quit()));
loop.exec();
)

37.4
QEventLoop, ,
. ( ) . ,
singleShot () ,
quit ( loop).
( 37.5), . 37.2, ,
.
.

12/4/2006 2:42:33

. 37.2.

Clock ( ptimer).
timeout!) siotUpdateDateTime ( ) ,
. start ( ) .
. siotUpdateDateTime ()
currentDateTime . , Qt::SystemLocaleDate
(. . 37.1), setText
.

37.5. Clock.h
#pragma once

#include <QtWidgets>

// -------- ---
============
class Clock : public QLabel {
Q OBJECT

public:
Clock(QWidget* pwgt = 0) : QLabel(pwgt)
37. , 539

{
QTimer* ptimer = new QTimer (this) ;
connect (ptimer, SIGNAL (timeout ()) , SLOT (slotUpdateDateTime ( ) ) ) ;
ptimer->start (500) ;
slotUpdateDateTime ( ) ;
}

public slots:
void slotUpdateDateTime ( )
(
QString str =
QDateTime: : currentDateTime ( ) . toString (Qt :: SystemLocaleDate) ;
setText ( "<H2XCENTER>" + str + "</CENTERX/H2>") ;
}
};

QBasicTimer
Qt
QBasicTimer, : isActiveO,
start , stop timerid ( ) ,
QTimer. start ( ) . ,
,
QObject, . ,
, QObject,
QOb j ect : : timerEvent ( ) .

QDate, QTime QDateTime ,


.
.
.
.
.
. ,
, , /
. .
, ,
.
.
38

...
.

.
, ,
. Qt, .
.
, , ,
.
.

, ,
. ,
.
, ,
. ,
, .
, .
, , ,
.

,
. ,
.
Qt- .
QProcess, QProcess.
, iODevice (. 36),
, ,
. , QProcess
.
, -
38. 541

,
. QProcess
. , error ( )
.
.
start (), ,
: . ,
started (), finished ().
finished () .
exitstatus () , :
NormalExit ( ) CrashExit ( ).

QProcess
: (stdout) (stderr).
setReadChannel {) .
, readyRead ( ) .
: readyReadStandardOutput ( )
readyReadStandardError ( )

QiODevice:
write ( ) , read ( ) , readLine ( ) getchar ( ) . ,
: readAHStandardOutput () readAHStandardError () .
QByteArray.
( 38.1), . 38.1,
QProcess. Command ()
, .
,
.

_ Command Shell l = |isiMa.n


Volume Serial Number is 6DB5-EDB3

Director/ of D:\Qt4\ehapter3-B\Process
01/21/2007 06:15 PM <DIR>
Cl/21/2007 06:15 PM cDIR>
01/21/2007 06:45 PM 5,255 Makefile _

01/21/2007 06:45 PM 4,517 Makefile.Debug


01/21/2007 06:45 PM 4,985 Makefile.Release
01/20/2007 07:01 PM 80 Process .pro
01, 21/2007 06:48 PM 2,585,852 Shell .exe I
01/20/2007 07:16 PM 2,338 Shell .h
01/21/2007 06:45 PM <DIR> debug
01/12/2007 08:04 AM 703 main.cpp
01/21/2007 06:45 PM <DIR> release
7 Fileis} 2,584,138 bytes
4 Dirts} 0 bytes free
Lommand: dir Enter

. 38.1.
542 VI. Qt

Shell QProcess.
readyReadStandardOutput ( ) slotDataOnStdout ( ) ,
readAllstandardOutput ()
.
m_ptxtDisplay append().
slotReturnPressed ( ) clicked () ( pcmd)
returnPressedO ( m_txtCommand).
Windows, dir, ,
cmd.
Windows cmd /.

, . start().

,
, startDetached().

start ( ) ,
, waitForStartedO waitForFinished( ) .
,
, , . :
QProcess ;
proc.start("cmd / " + strProgram);
proc.waitForStarted();

38.1. shell.h

class Shell : public QWidget {


Q_OBJECT
private:
QProcess* m_process;
QLineEdit* m_ptxtCommand;
QTextEdit* m_ptxtDisplay;

public:
//
Shell(QWidget* pwgt = 0) : QWidget(pwgt)
{
m_process = new QProcess(this);
m_ptxtDisplay = new QTextEdit;

QLabel* plbl = new QLabel("&Command:");

m_ptxtCommand = new QLineEdit("dir");


plbl->setBuddy(m_ptxtCommand);

QPushButton* pcmd = new QPushButton("SEnter);

connect(m_process,
SIGNAL(readyReadStandardOutput()),
38. 543

SLOT(slotDataOnStdout())
);
connect(m_ptxtCommand,
SIGNAL(returnPressed()),
SLOT(slotReturnPressed())
);
connect(pcmd, SIGNAL(clicked()), SLOT(slotReturnPressed()));

//Layout setup
QHBoxLayout* phbxLayout = new QHBoxLayout;
phbxLayout->addWidget(plbl);
phbxLayout->addWidget(m_ptxtCommand);
phbxLayout->addWidget(pcmd);

QVBoxLayout* pvbxLayout = new QVBoxLayout;


pvbxLayout->addWidget(m_ptxtDisplay);
pvbxLayout->addLayout(phbxLayout);
setLayout(pvbxLayout);

public slots:
//
void slotDataOnStdout()
{
m_ptxtDisplay->append(m_process->readAHStandardOutput());
}

//
void slotReturnPressed()
{
QString strCommand = "";
#ifdef Q_WS_WIN
StrCommand = "cmd /
#endif
strCommand += m_ptxtCommand->text();
m_process->start(strCommand);

.
Qt QThread. ,
.
,
, .
,
( ). ,
. , -
544 VI. Qt

, ,
. ,
, .
.
,
,
, .
,
,
. ,
,
.
, ,
, . ,
, , ,
,
. ,
, .
.
.
,
. ,
, .

. , ,
. .
, ,
, . ,
:
, . ,
, , .
,
, .
,
, Qt.
.
- ?
QThread run(),
, . :
class MyThread : public QThread {
public:
void run()
{
// ,
}
}


start ( ) , , , run().
38. 545

:
MyThread thread;
thread.start();

, ,
. :
, .
: IdlePriority, LowestPriority, LowPriority,
NormalPriority. ,
, , -
;
: HighPriority HighestPriority.
.
- ;
TimeCriticalPriority.
. ,
,
.
,
start(). :
MyThread thread;
thread.start(QThread::IdlePriority);

, ,
priority().
setPriority().

!
Linux ,
.
, . Windows :
, ,
, ,
,
- , , .



. , , ,
, ?
(. 38.2).
.
: .
546 VI. Qt

. 38.2.


- ,
.


, ,
,
. QTimer (. 37)
(. 39).
,
( ) run ( ) .
quit( ) exit ( ) . ,
main ( ).
QObject , . ,
QObject, ,
. QObject::thread().
. ,
. ,
QThread::currentThreadld ( ) .

QThread: : currentThreadld ( ).
,
, .

QObject:-.moveToThread().

-
,
. 2 , connect ( )
.
38. 547

Qt : : Autoconnection, .
, Qt ,
. ,
. , ,
. Qt
, , ,
, .
, , . ,
,
.
, -
QThread. , QThread
, ,
. , , (. 2)
,
( )
QObject: rmoveToThread ( ) . QThread QObject , ,
Qt. ,
QThread
, main ( ) ,
, , ,
.
, , ,
,
QObject: :moveToThread() . ,
( 38.2-38.4).
(. 38.3) 10 0, . -
,
.

. 38.3. -

MyWorker ( 38.2) ,
. QObject,
Q OBJECT, .
m nvalue
(m_timer) slotNextValue ( ) .
slotNextValue () m nvalue
valueChanged ( ) . ,
finished (), .
doWork ( ) .
548 VI. Qt

38.2. MyThread.h. MyWorker

class MyWorker : public QObject {


Q_OBJECT
private:
int m_nValue;
QTimer m timer;

public:
MyWorker(QObject* pobj = 0) : QObject(pobj)
, m nValue(lO)

connect(&m_timer, SIGNAL(timeout()), SLOT(setNextValue()));


}

void doWork()
{
m_timer.start(1000);
}

signals:
void valueChanged(int);
void finished ( );

public slots:
void setNextValue()
{
emit valueChanged( m_nValue);
if(!m_nValue){
emit finished();

38.3 MyThread .
MyThread
run ( ) ,
( ) . ( )
,
run ( ) , . main(),
,
QApplication::() ,
Qt- .

38.3. main.cpp. MyThread

class MyThread : public QThread {


Q_OBJECT
public:
MyThread()
38. 549

{
}

void run()
{
exec();

};

38.4 ,
led, thread MyWorker,
. , ,
valueChanged ( ) MyWorker
display(). moveToThread ( ) MyWorker
finished () quit ()
, .
finished( ) quit()
. start( )
MyWorker::doWork( ).

38.4. main.cpp. man()

int main(int arge, char** argv)


{
QApplication app(argc, argv);
QLCDNumber led;
MyThread thread;
MyWorker worker;

QObject::connect(Sworker, SIGNAL(valueChanged(int) ),
Sled, SLOT(display(int))
);

led.setSegmentStyle(QLCDNumber::Filled);
led.display(10);
led.resize(220, 90);
led.show();

worker.moveToThread(&thread);
QObject::connect(&worker, SIGNAL(finished()),
sthread, SLOT(quit())
);
QObject: -.connect(&thread, SIGNAL(finished()),
&app, SLOT(quit())
);

thread.start();
550 VI. Qt

worker.doWork();
return app.exec();
}

,
.
.
( 38.5 38.6), . 38.4,
, .

. 38.4. ,

run(), 38.5, 0 100,


100 progress ()
. 100
QThread::usleep(),
.

38.5. main.cpp. MyThread

class MyThread : public QThread {


Q_OBJECT

public:
void run()
{
for (int i = 0; i <= 100; ++i) {
usleep(100000);
emit progress(i);

signals:
void progress(int);
};

38.6
thread, progress ( )
setvalue ( ) .
start().

38.6. main.cpp. man()

int main(int argc, char** argv)


{
QApplication app(argc, argv);
38. 551

QProgressBar prb;
MyThread thread;

QObject::connect(sthread, SIGNAL(progress(int)),
&prb, SLOT(setValue(int))
);

prb.show();

thread.start();

return app.exec();
}
#include "main.moc"



. 16, :
QCoreApplication::postEvent ( ) QCoreApplication::sendEvent ( ) .
, : postEvento
, sendEvent ( ) .
postEvent () . . 38.5 ,

. , , ,
. . ,
, , .

1 ... 2
1
1 ... 1 ...

( (
V t
V
2

. 38.5.

,
QObject::event().
, ,

.
( 38.7-38.10), ,
38.5 38.6 (. . 38.4).
, , ,
( 38.7). QEvent
m nvalue.
value ( ) setValue ( ) . ,
QEvent().
552 VI. Qt

38.7. main.cpp. ProgressEvent

class ProgressEvent : public QEvent {


private:
int m_nValue;

public:
enum {ProgressType = User + 1};

ProgressEvent() : QEvent((Type)ProgressType)
{
}

void setValue(int n)
{
m_nValue = n;
}

int value() const


{
return m_nValue;
}
};

38.8 MyThread .
, - ,
-
postEvent ( ) . run ( )
(memory leak), ,
.


, ,
,
. . .
, - QObject::
connecto. , ,
.
(. 38.2).

38.8. main.cpp.

class MyThread : public QThread {


private:
QObject* m_pobjReceiver;

public:
MyThread(QObject* pobjReceiver) : m_pobjReceiver(pobjReceiver)
{
}
38. 553

void run()
{
for (int i = 0; i <= 100; ++i) {
usleep(100000);

ProgressEvent* pe = new ProgressEvent;


pe->setValue(i);
QApplication::postEvent(m_pobjReceiver, pe);


, .
(. 15).

customEvent ( ) .
38.9. customEvent ( ) ,
ProgressType, ProgressEvent,
value ().
QProgressBar::setvalue () .

38.9. main.cpp. MyProgressBar

class MyProgressBar : public QProgressBar {


public:
MyProgressBar(QWidget* pwgt = 0) : QProgressBar(pwgt)
{
}

void customEvent(QEvent* pe)


{
if ((int)pe->type() == ProgressEvent::ProgressType) {
setvalue(((ProgressEvent*)(pe))->value());
}
QWidget::customEvent (pe);

, 38.10,
thread,
start().

38.10. main.cpp. main()

int main(int argc, char** argv)


{
QApplication app(argc, argv);
MyProgressBar prb;
MyThread thread(&prb);
554 VI. Qt

prb.show();

thread.start();

return app.exec();
}

(. 38.5 38.6)
(. 38.7-38.10), ,
. , ,
. , .
, .

,
. , ,
. , ,
. :
, - ,
. ,
, , -
, ,
. ,
, .
.
(critical sections),
. ,
, ,
. ,
, ,
. , ,
, .

(mutex) , ,
. ,
, ,
, .
,
. , . -
, ,
. , ,
. , ,
, . .


,
, .
38. 555

, ,
. QMutex. lock ( ) QMutex
. unlock ( ) ,
.
QMutex tryLock(). ,
, .
false,
, .
true, , ,
.
( 38.11),
(thread safety).

38.11.

class ThreadSafeStringStack {
private:
QMutex m_mutex;
QStack<QString> m_stackString;

public:
void push(const QStrings str)
{
m_mutex.lock();
m_stackString.push(str);
m_mutex.unlock();
}

QString pop()
{
QMutexLocker locker(&m_mutex);
return m_stackString.empty() ? QString()
: m_stackString.pop();

ThreadSafeStringStack, 38.11, ,
, push ( ) , , , pop ( ) ,
. private : m mutex
. , QStack<T>
.
QStack<T> , -
, . push ( )
lock ( ) , ,
unlock () .
,
.
pop ( ) QMutexLocker.
. QMutexLocker
.
556 VI. Qt

, . ,
, push ( ) ,
, .

: , ,
. , ,
, . ,
, , .
,
, . ,

. Qt
.

. ,
,
. . ,
,
. ,
, ,
. .
. , ,
. ,
, . ,
, .
QSemaphore. .
QMutex, lock()
unlock () acquire () release () :
QSemaphore sem(1);
sem.acquire();
. acquire ()
, .
, .
.
acquire (), , ,
, .
acquire ( ) , ,
.
release( ) .
.
tryAcquireO
.


Qt QWaitCondition,
. ,
.
38. 557

, QWaitCondition: : wait
. , ,
, QWaitCondition: rwakeOne QWaitCondition: :wakeAll () .
, ,
. ,
. wait()
, .


,
, . ,
,
.
. , , ,
. ,
, .
. ,
.
(deadlock) (. 38.6).
. , ,
, ,
, .

-0
%

% \0<*

. 38.6.

QtConcurrent
,
, ,
, .
558 VI. Qt

Qt QtConcurrent.
,
.
, .
pro- :
QT += concurrent
, ,
QtConcurrent::run ( ) ,
38.12.

38.12. main.cpp. QtConcurrent

# include <QtCore>
# include <QtConcurrent/QtConcurrent

//
QString myToUpper(const QStrings str)
{
return str.toUpper();
}

//
int main(int argc, char** argv)
{
QCoreApplication app(argc, argv);

QFuture<QString> future =
QtConcurrent::run(myToUpper, QString("test"));
future.waitForFinished();
qDebug() future.result();

return 0;
}

, , ,
. , ,
. . run ( ) . myToUpper ( )
.
QFuture, , . ,

, .
QFuture , .
, , QString. ,
waitForFinished( ) QFuture
, .
QFuture ,
, :
;
QFuture : : isFinished ( )
QFuture::isRunning( ) ;
38. 559

QFuture::isStarted ( ) ;

QFuture::isPaused() QFuture::pause().
, ,
( ) .
Qt Concurrent ::mapped () .
, ( ) .
main() 38.12 ( 38.13).

38.13. main.cpp. QtConcurrent

int main(int argc, char** argv)


{
QCoreApplication app(argc, argv);

QStringList 1st (QStringList ( ) "one" "two" "three");


QFuture<QString> future =
QtConcurrent ::mapped (1st .begin () , Ist.endO, myToUpper);
future.waitForFinished( ) ;
qDebug ( ) .
future results ( ) ;

return 0;
}

38.13
QtConcurrent : ;mapped ( ) . ,
() . ,
, QFuture: :
wait ForFinished ()
. :
"ONE", "TWO", "THREE"

,
. , .
.
.

, .
,
, .
,
.
QThread
run , .
, start ( ) .
, ( ) run ( ) .
560 VI. Qt


.
.

. Qt QMutex,
QWaitContion QSemaphore.
Qt
.
QtConcurrent

.
39


, .
. ,


( , socket , )
. ,
, ,
.
- (point to point),
.
(datagram) (stream).
.
.
, , - ,
, .
, ,
, ,
.
Qt QUdpSocket,
QTcpSocket.

QTcpSocket TCP (Transmition Control Protocol,


) ,
.

.
: HTTP, FTP, POP3, SMTP,
. QAbstractSocket, , ,
QiODevice. , ( )
QiODevice QDataStream
QTextStream (. 36).
QTcpSocket ,
. ,
, waitFor.
562 VI. Qt

.
.
QUdpSocket UDP (User Datagram Protocol,
). ,

. , ,
,
,
. UDP ,
TCP,
.
UDP
, .
, , ,
, . ,
,
. , UDP , .
, , .
: TCP
UDP. , .

TCP,
UDP.

-
- : ,
(. 39.1). , ,
, . ,
IP- ,
. ,
, ,
. ,
. ,
, .
.

V \\ *

. 39.1. -
39. 563

.
(. 39.1).

39.1.

11 systat

21 FTP

22 SSH

23 Telnet

25 SMTP

53 DNS

80 HTTP Web- ( 8080 8000)

110 POP3

139 Netbios-SSN

143 IMAP

194 IRC -

443 HTTPS HTTP

5800 VNC

5900 VNC

8080 Web -

-
Qt QTcpServer,
-. ( 39.1-39.6),
. 39.2, ,
.

""*"1 MyServer
| g| jj

Server

. 39.2.

564 VI. Qt

39.1 . ,
39.2-39.6 MyServer,
, .
, 2323.

39.1. main.cpp

#include <QtWidgets>
#include "MyServer.h"

int main(int argc, char** argv)


{
QApplication app(argc, argv);
MyServer server(2323);

server.show();

return app.exec();
}

MyServer, 39.2, m ptcpServer,


. m nNextBlockSize
.
m ptxt .

39.2. MyServer.h

#pragma once

#include <QWidget>

class QTcpServer;
class QTextEdit;
class QTcpSocket;

/ / =================================
class MyServer : public QWidget {
------- =================

Q_OBJECT
private:
QTcpServer* m_ptcpServer;
QTextEdit* m_ptxt;
quintl6 m_nNextBlockSize;

private:
void sendToClient(QTcpSocket* pSocket, const QStrings str);

public:
MyServer(int nPort, QWidget* pwgt =0);
39. 565

public slots:
virtual void slotNewConnection ( );
void slotReadClient ();
};

listen () ( 39.3).
, .
, ,
false, .
, (. 39.4)
slotNewConnection newConnectiont),
.
(
mjotxt) setReadOnly ( ) ,
.

39.3. MyServer.cpp. MyServer

MyServer::MyServer (int nPort, QWidget* pwgt /*=0*/) : QWidget (pwgt)


, m_nNextBlockSize(0)
{
m_ptcpServer = new QTcpServer(this);
if ( !m_ptcpServer->listen(QHostAddress::Any, nPort)) {
QMessageBox::critical(0,
"Server Error",
"Unable to start the server:"
+ m_ptcpServer->errorString ()
);
m_ptcpServer->close ( );
return;
}
connect (m_ptcpServer, SIGNAL(newConnection() ),
this, SLOT (slotNewConnection() )
);

m_ptxt = new QTextEdit;


m_ptxt->setReadOnly(true);

//Layout setup
QVBoxLayout* pvbxLayout = new QVBoxLayout;
pvbxLayout->addWidget (new QLabel("<Hl>Server</Hl>") );
pvbxLayout->addwidget (m_ptxt);
setLayout (pvbxLayout);
)

slotNewConnection!), 39.4,
.
nextPendingConnectionf), ,
. -
566 VI. Qt

- . disconnected () ,
, QObject: rdeleteLater () ,
.
readyToRead ( ) , slotReadClient().

39.4. MyServer.cpp. slotNewConnection ()

/*virtual*/ void MyServer::slotNewConnection()


{
QTcpSocket* pClientSocket = m_ptcpServer->nextPendingConnection();
connect(pClientSocket, SIGNAL(disconnected()),
pClientSocket, SLOT(deleteLater())
);
connect(pClientSocket, SIGNAL(readyRead()),
this, SLOT(slotReadClient())

sendToClient(pClientSocket, "Server Response: Connected!");


}

39.5 ,
sender ( ) , QTcpSocket. for ,
.
, , .
. ,
m_nNextBlockSize
( ).
, time str.
time toStringO
str strMessage,
append ( ) .
m_nNextBlockSize 0, ,
. sendToClient () ,
.

39.5. MyServer.cpp. slotReadClient()

void MyServer::slotReadClient()
{
QTcpSocket* pClientSocket = (QTcpSocket*)sender();
QDataStream in(pClientSocket);
in.setVersion(QDataStream::Qt_5_3);
for (;;) {
if (!m_nNextBlockSize) {
if (pClientSocket->bytesAvailable() < sizeof(quintl6)) {
break;
}
in m_nNextBlocksize;
}
39. 567

if (pClientSocket->bytesAvailable () < m_nNextBlockSize) {


break;
}
QTime time;
QString stra
in time str;

QString strMessage =
time.toSt ring () + " " + "Client has sent " + str;
m_ptxt->append(strMessage);

m_nNextBlockSize =0;

sendToClient (pClientSocket,
"Server Response: Received \"" + str + "\"
);

sendToClient () , (
39.6). , ,
, , ,
. .
arrBlock QByteArray.
QDataStream, ,
0. seek(),
arrBlock, sizeof(quintl6),
(out) , .
write ( ).

QTextstream.
QDataStream,
. ,
QTime. QDataStream,
, , . .

39.6. MyServer.cpp. sendToClient ()

void MyServer::sendToClient (QTcpSocket* pSocket, const QStrings str)


{
QByteArray arrBlock;
QDataStream out (sarrBlock, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_5_3);
out quintl6(0) QTime::current Time() str;

out.device ()->seek ( 0 );
out quint 16(arrBlock.size ( ) sizeof(quintl6) );

pSocket->write(arrBlock);
568 VI. Qt

-
QTcpSocket,
connectToHost ( ) , ( IP-),
. QTcpSocket
, , connected ( ) .
error(int) , QAbstractSocket::
SocketError. , , ,
.
QTcpSocket .
( 39.7-39.13)
(. 39.3). ,
, Send ().

, lent
Client
Received the connectedO signal
18:20:02 Server Response: Connected!
18:20:57 Server Response: Received "Testl"
18:21:06 Server Response: Received "Test2"
18:21:16 Server Response: Received "Tests"

|Test4|
Send

. 39.3.

main (), 39.7, (.


39.8-39.13). ,
"localhost".
2323, , .

39.7. main.cpp
#include <QApplication>
#include "MyClient.h"

int main(int argc, char** argv)


{
QApplication app(argc, argv);
MyClient client("localhost", 2323);

client.show();

return app.exec();
39. 569

MyClient, 39.8, m pTcpSocket,


, m_nNextBlockSize,
.
: m txtinfo m txt input .

39.8. MyClienth

#pragma once

# include <QWidget>
# include <QTcpSocket>

class QTextEdit;
class QLineEdit;

// =================================================================
class MyClient : public QWidget {
Q_OBJECT
private:
QTcpSocket* mjpTcpSocket;
QTextEdit* mjptxtlnfo;
QLineEdit* m_ptxt Input;
quint 16 m_nNextBlockSize;

public:
MyClient (const QStrings strHost, int nPort, QWidget* pwgt = 0) ;

private slots:
void slotReadyRead ( );
void slotError (QAbstractSocket::SocketError);
void slotSendToServer ( );
void slot Connected ( );
};

39.9 ,
( m_pTcpSocket). connectToHost ( ) ,
. ,
. .
connected ( ) , , readyRead ( )
.
slotConnected ( ) slotReadyRead ( ).
error (), slotError (),
.
, , ,
. clicked ()
slotSendToServer ( ) MyClient,
.
<Enter>, returnPressedO
(m_ptxt Input) SlotSendToServer().
570 VI. Qt

39.9. MyClient.cpp. MyClient

MyClient::MyClient(const QStrings strHost,


int nPort,
QWidget* pwgt /*=0*/
) : QWidget(pwgt)
, m_nNextBlockSize(0)
{
m_pTcpSocket = new QTcpSocket(this);

m_pTcpSocket->connectToHost(strHost, nPort);
connect(m_pTcpSocket, SIGNAL(connected()), SLOT(slotConnected()));
connect(m_pTcpSocket, SIGNAL(readyRead()), SLOT(slotReadyRead()));
connect(m_pTcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
this, SLOT(slotError(QAbstractSocket::SocketError))
);

m_ptxtInfo = new QTextEdit;


m_ptxtlnput = new QLineEdit;

m_ptxtInfo->setReadOnly(true);

QPushButton* pcmd = new QPushButton("&Send");


connect(pcmd, SIGNAL(clicked()), SLOT(slotSendToServer()));
connect(m_ptxtlnput, SIGNAL(returnPressed()),
this, SLOT(slotSendToServer())
);

//Layout setup
QVBoxLayout* pvbxLayout = new QVBoxLayout;
pvbxLayout->addWidget(new QLabel("<Hl>Client</Hl>"));
pvbxLayout->addWidget(m_ptxtlnfo);
pvbxLayout->addWidget(m_ptxtlnput);
pvbxLayout->addWidget(pcmd);
setLayout(pvbxLayout);

39.10 slotReadyToRead ( ) ,
. for ,
. , ,
, .
.
, ,
QDataStream ( in).
.
( m ptxtinfo) append().
m nNextBiockSize 0,
, .
39. 571

39.10. MyClientxpp. slotReadyRead ()

void MyClient::slotReadyRead()
{
QDataStream in(mjpTcpSocket);
in.setVersion(QDataStream::Qt_5_3);
for (;;) {
if (!m_nNextBlocksize) {
if (m_pTcpSocket->bytesAvailable() < sizeof(quintl6)) {
break;
}
in m_nNextBlocksize;
}

if (m_pTcpSocket->bytesAvailable() < m_nNextBlockSize) {


break;
}
QTime time;
QString stra
in time str;

m_ptxtInfo->append(time.toString() + " " + str);


m nNextBlockSize = 0;

slotErrorO, 39.11, .
,
.

39.11. MyClientxpp. slotErrorO

void MyClient::slotError(QAbstractSocket::SocketError err)


{
QString strError =
"Error: " + (err == QAbstractSocket::HostNotFoundError ?
"The host was not found." :
err == QAbstractSocket::RemoteHostClosedError ?
"The remote host is closed." :
err == QAbstractSocket::ConnectionRefusedError ?
"The connection was refused." :
QString(m_pTcpSocket->errorString())
);
m_ptxtInfo->append(strError);
}

39.12 .
, (. 39.6),
. MyServer::sendToClient () ,
572 VI. Qt

,
setText ( ) (
clear()).
, - slotSendToServer()
Send () <Enter>
( m_ptxtinput()).

39.12. MyClient.cpp. slotSentToServer ()

void MyClient::slotSendToServer()
{
QByteArray arrBlock;
QDataStream out(&arrBlock, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_5_2);
out quintl6(0) QTime::currentTime() m_ptxtInput->text ();

out.device()->seek(0);
out quintl6(arrBlock.size() sizeof(quintl6));
m_pTcpSocket->write(arrBlock);
m_ptxtInput->setText("");
}

, slotConnectedO.
( 39.13).

39.13. MyClient.cpp. slotConnectedO

void MyClient::slotConnected()
{
m_ptxtInfo->append("Received the connected() signal");
}

UDP- UDP-
UDP- QUdpSocket.
writeDatagramO.
, QUdpSocket,
bind ( ) . , ,
, readyRead ( ) .
readDatagram().

, . ,
.
UDP- UDP- ,
39.14-39.19.
, (. 39.4).
39. 573

r 'I UdoClient 11
Sent:C6 19, 20:26:47 2011 Received:Cb 19. 20:26:47 2011 *
Sent:C6 19. 20:26:47 2011 Received:C6 19. 20:26:47 2011
Sent:C6 19, 20:26:48 2011 Received:Cb 19. 20:26:48 2011
Sent:C6 19. 20:26:48 2011 Received:Cb 19. 20:26:48 2011
5ent:C6 19. 20:26:49 2011 Received:C6 19. 20:26:49 2011
SentiCb 19. 20:26:49 2011 Received:C6 19. 20:26:49 2011
5ent:C6 19, 20:26:50 2011 Received:C6 19. 20:26:50 2011
Sent:Cb 19. 20:26:50 2011 Received:C6 19. 20:26:50 2011
Sent:C6 19, 20:26:51 2011 Received:C6 19. 20:26:51 2011
Sent:Cb 19. 20:26:51 2011 Received:C6 19. 20:26:51 2011
5ent:C6 19, 20:26:52 2011 Received:C6 19. 20:26:52 2011
Sent :Cb 19. 20:26:52 2011 Received:C6 19. 20:26:52 2011 IH
Sent:C6 19, 20:26:53 2011 Received:C6 19. 20:26:53 2011
5ent:C6 19, 20:26:53 2011 Received:CS 19. 20:26:53 2011|
--
. 39.4. UDP- UDP-

. udpServer
QUdpSocket ( 39. 14), : m_pudp.
: slotSendDatagram().

39.14. UdpServer.h

class UdpServer : public QTextEdit {


Q_OBJECT
private:
QUdpSocket* m_pudp;

public:
UdpServer(QWidget* pwgt = 0);

private slots:
void slotSendDatagram();
};


UdpServer ( 39.15), setwindowTitle ( )
QUdpSocket.
, ,
0,5 , start
slotSenDatagramf).

39.15. UdpServer.cpp. UdpServer

UdpServer::UdpServer(QWidget* pwgt /*=0*/) : QTextEdit (pwgt)


{
setwindowTitle("UdpServer");

m_pudp = new QUdpSocket(this);

QTimer* ptimer = new QTimer(this);


ptimer->setInterval(500);
574 VI. Qt

ptimer->start();
connect(ptimer, SIGNAL(timeout()), SLOT(slotSendDatagram()));

39.16 slotSendDatagramO,
. .
QDataStream baDatagram.
writeDatagram ( ) ,
baDatagram, :
IP- . IP-,
QHostAddress::LocalHost,
127.0.0.1.

QAbstractSocket QUdpSocket
IP-. IP-
, fromName QHostName.

39.16. UdpServer.cpp. slotSendDatagramO

void UdpServer::slotSendDatagram()
{
QByteArray baDatagram;
QDataStream out (sbaDatagram, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_5_3);
QDateTime dt = QDateTime::currentDateTime();
append("Sent:" + dt.toString());
out dt;
m_pudp->writeDatagram(baDatagram, QHostAddress::LocalHost, 2424);
}

.
UDP- ( 39.17). ,
QUdpSocket, m_pudp.
slotProcessDatagrams ( ) ,
.

39.17. UdpCIient.h

class UdpClient : public QTextEdit {


Q_OBJECT
private:
QUdpSocket* m_pudp;

public:
UdpClient(QWidget* pwgt = 0);

private slots:
void slotProcessDatagrams();
>;
39. 575

,
"udpClient" ( 39.18). QUdpSocket
bind() 2424.
IP- ,
.
readyRead ( ) slotProcessDatagrams ().

39.18. UdpCIientcpp. UdpClient

UdpClient ::UdpClient (QWidget* pwgt /*=0*/) : QTextEdit (pwgt )


{
setWindowTitle("UdpClient");

m_pudp = new QUdpSocket (this);


m_pudp->bind(2424);
connect (m_pudp, SIGNAL(readyRead ( ) ), SLOT (slotProcessDatagrams ( )) ) ;

39.19 QUdpSocket

. ,
,
. do...while ,
, ,
.
pendingDatagramSize () .
, ,
. ,
, .

readDatagram ( ) baDatagram.
in , , .
QTextEdit::append ( ).

39.19. UdpCIientcpp. slotProcessDatagrams ()

void UdpClient::slotProcessDatagrams ( )
{
QByteArray baDatagram;
do {
baDatagram.resize(m_pudp->pendingDatagramSize ( ));
m_pudp->readDatagram(baDatagram.data (), baDatagram.size ());
} while(m_pudp->hasPendingDatagrams ());

QDateTime dateTime;
QDataStream in ( sbaDatagram, QIODevice::Readonly);
in.setVersion(QDataStream::Qt_5_3);
in dateTime;
append (" Received:" + dateTime.toString ());
576 VI. Qt


, QHttp QFtp,
, .

. ,
(cookie), (proxy), ,
.
: QNetworkAccessManager, QNetworkRequest
QNetworkReply.
QNetworkAccessManager . , :
head ;
get ;
put ;
post get put, HTTP.
.
.
QNetworkRequest ,
URL. , , -
.
QNetworkReply , URL, HTTP-
, . . :
readyRead ( )
;
finished ( ) ;

error ( ) ;
downloadProgress() uploadProgress() .
QNetworkRequest QNetworkReplay :
QNetworkRequest
, a QNetworkReply

.
,
HTTP, ( 39.20-39.31)
(. 39.5), .
( 39.20)
DownloaderGui show ( ) .

39.20. main.cpp.

#include <QApplication>
#include "DownloaderGui.h"

int main(int argc, char** argv)


{
QApplication app(argc, argv);
DownloaderGui downloader;
39. 577

downloader.show();

return app.exec();

. 39.5.

, 39.21, QObject
QNeworkAccessManager,
. download () ,
QUri. ,
: downloadProgress(), done() error (). slotFinished( )
done ( ) error().

39.21. Downloader.h

#pragma once

#include <QObject>
#include <QUrl>

class QNetworkAccessManager;
class QNetworkReply;

/ / =============================
class Downloader : public QObject {
Q OBJECT

private:
QNetworkAccessManager* m_pnam;
578 VI. Qt

public:
Downloader(QObject* pobj = 0);

void download(const QUrls);

signals:
void downloadProgress(qint64, qint64 );
void done (const QUrls, const QByteArrayS);
void error ( );

private slots:
void slotFinished(QNetworkReply*);
);

39.22 QNetworkAccessManager
finished () slotFinishedO .
QNetworkReply,
.

39.22. Downloader.cpp.

Downloader::Downloader(QObject* pobj/*=0*/) : QObject(pobj)


{
m_pnam = new QNetworkAccessManager(this);
connect(m_pnam, SIGNAL(finished(QNetworkReply*)),
this, SLOT(slotFinished(QNetworkReply*))
);

download)), 39.23,
QNetworkRequest,
QNetworkAccessManager. get ( ) .
,
, QNetworkReply,
, ,
downloadProgress().

39.23. Downloader.cpp. downloadO

void Downloader::download(const QUrls url)


{
QNetworkRequest request(url);
QNetworkReply* pnr = m_pnam->get(request);
connect(pnr, SIGNAL(downloadProgress(qint64, qint64)),
this, SIGNAL(downloadProgress(qint64, qint64))
);
)

slotFinishedO ( 39.24).
, ,
39. 579

error () , QNetworkReply::NoError,
, error ( ) . ,
, done ( ) .
URL . QNetworkReply
readAll () . QNetworkReply,
, .
deleteLater ( ) , ,
delete C++ (
deleteLater () ,
). , ,
.

39.24. Downloader.cpp. slotFinished()

void Downloader::slotFinished(QNetworkReply* pnr)


{
if (pnr->error() != QNetworkReply::NoError) {
emit error();
}
else {
emit done(pnr->url(), pnr->readAll());
}
pnr->deleteLater();
}

, . 39.5 39.25,
( ), (
m ptxt) ( m_pcmd). ,
Downloader ( m_dl).
showPicO
. :
slotGo() ;
slotError ;
()

slotDownloadProgress {) ,
;
slotDone ( ) .

39.25. DownloaderGui.h

#pragma once

#include <QWidget>
#include <QUrl>

class Downloader;
class QProgressBar;
class QLineEdit;
class QPushButton;
580 VI. Qt

// ===========================================================
class DownloaderGui : public QWidget {
Q_OBJECT

private:
Downloader* m_pdl;
QProgressBar* m_ppb;
QLineEdit* m_ptxt;
QPushButton* m_pcmd;

void showPic(const QStrings);


public:
DownloaderGui(QWidget* pwgt = 0);

private slots:
void slotGo ( );
void slotError ( );
void slotDownloadProgress(qint64, qint64 );
void slotDone (const QUrl&, const QByteArrayS);
};

, 39.26,
, Downloader. setText ( )
strDownloadLink,
.
slotGo ( ) , downladProgress ( )
Downloader slotDownloadProgress ( )
slotDone ( ) .
QGridLayout.

39.26. DownloaderGui..

DownloaderGui::DownloaderGui(QWidget* pwgt /*=0*/) : QWidget(pwgt)


{
m_pdl = new Downloader(this);
m_ppb = new QProgressBar;
m_ptxt = new QLineEdit;
m_pcmd = new QPushButton(tr("&Go"));

QString strDownloadLink =
"http://www.neonway.com/wallpaper/images/traderstar.jpg";
m_ptxt->setText(strDownloadLink);

connect(m_pcmd, SIGNAL(clicked()), SLOT(slotGo()));


connect(m_pdl, SIGNAL(downloadProgress(qint64, qint64)),
this, SLOT(slotDownloadProgress(qint64, qint64))
);
connect(m_pdl, SIGNAL(done(const QUrl&, const QByteArray&)),
this, SLOT(slotDone(const QUrl&, const QByteArray&))
39. 581

QGridLayout* pLayout = new QGridLayout;


pLayout->addWidget(m_ptxt, 0, 0);
pLayout->addWidget(m_pcmd, 0, 1);
pLayout->addWidget(m_ppb, 1, 0, 1, 1);
setLayout(pLayout);
}

39.27 . ,
download ( ) (
text ( ) )
, , .

39.27. DownloaderGui.cpp. slotGo()

void DownloaderGui::slotGo()
{
m_pdl->download(QUrl(m_ptxt->text()));
}

39.28
, , nTotai,
. ,
,
.
, , , ,
. slotErrorO,
, . ,
setvalue ( )
.

39.28. DownloaderGui.cpp. slotDownloadProgress()

void DownloaderGui::slotDownloadProgress(qint64 nReceived, qint64 nTotai)


{
if (nTotai <= 0) {
slotError();
return;
}
m_ppb->setValue(100 * nReceived / nTotai);

slotDoneO ( 39.29).
, , , (link), (
url), ( ). .
,
. ,
JPG PNG, , ,
showPic ( ) , .
582 VI. Qt

39.29. DownloaderGui.cpp. slotDoneO

void DownloaderGui: rslotDone(const QUrl& url, const QByteArrayS ba)


{
QFile file(url.path().section('/', -1));
if (file.open(QIODevice::WriteOnly)) {
file.write(ba);
file.close();

if (strFileName.endsWith(".jpg")
II strFileName.endsWith(".png")
){
showPic(strFileName);

( 39.30) ,
3
scaled () Qt::SmoothTransforamtion.
setPixmapO QLabel
setFixedSize () .
show().

39.30. DownloaderGui.cpp. showPic()

void DownloaderGui::showPic(const QStrings strFileName)


{
QPixmap pix(strFileName);
pix = pix.scaled(pix.size() / 3,
Qt::IgnoreAspectRatio,
Qt::SmoothTransformation
);
QLabel* plbl = new QLabel;
plbl->setPixmap(pix);
plbl->setFixedSize(pix.size());
plbl->show();

, 39.31,
.

39.31. DownloaderGui.cpp. slotError()

void DownloaderGui::slotError()
{
QMessageBox::critical(0,
tr("Error"),
tr("An error while download is occured")
);
}
39. 583


, , ,
, .
.
. , ,
.

, waitFor. ..
QAbstractSocket , :
waitForConnected ( ) ;
waitForReadyRead ( ) ;
, ;
waitForBytesWritten ( )
waitForDisconnected() ;
waitForEncrypted() ( QSslSocket).
, .
30 .
TCP- ,
39.32.

39.32. TCP-

int main(int argc, char** argv)


{
QCoreApplication app(argc, argv);
QTcpServer tcpServer;
int nPort = 2424;

if (!tcpServer.listen(QHostAddress::Any, nPort)) {
qDebugO "Can't listen on port: " nPort;
return 0;
}

forever {
while (tcpServer.waitForNewConnection(60000)) {
do {
QTcpSocket* pSocket = tcpServer.nextPendingConnection();
QString strDateTime =
QDateTime::currentDateTime()
.toString("yyyy.MM.dd hhrmm:ss");
pSocket->write(strDateTime.toLatinl());
pSocket->flush();
qDebugO "Server date & time:" + strDateTime;
pSocket->disconnectFromHost();
if (pSocket->state() == QAbstractSocket::ConnectedState){
pSocket->waitForDisconnected();
}
584 VI. Qt

delete pSocket;
} while (tcpServer.hasPendingConnections());

return 0;
}

39.32 ,
, .
QTcpServer , ,
2424.

!
Mac OS X , 80 (HTTP),
. -
sudo.

forever while
, ,
, .

nextPendingConnection () , pSocket.
strDateTime,
write ( ) . write ( )
flush ( ) , , ,
. ,
, disconnectFromHost ( )
, .
waitForDisconnectedO . ,
waitForDisconnectedO ,
:
QAbstractSocket::waitForDisconnectedO is not allowed in UnconnectedState
, ,
QAbstractSocket::ConnectedState,
, waitForDisconnectedO .
delete .
, , ,
, .
, ,
,
forever.
TCP-, 39.33, .
(socket) connectToHost () .
QHostAddress::LocalHost ,
, .
, .
waitForDisconnectedO , .
.
39. 585

39.33. TCP-

#include <QtCore>
#include <QtNetwork>

int main(int argc, char** argv)


{
QCoreApplication app(argc, argv);
QTcpSocket socket;

socket.connectToHost(QHostAddress::LocalHost, 2424);
socket.waitForDisconnected();
qDebugO socket.readAll();

return 0;
}

QNetworkAccessManager
waitFor. . . . ,
.
39.25 , download () ,
,
:
void Downloader::download(const QUrl& url)
{
QNetworkRequest request(url);
QNetworkReply* pnr = m_pnam->get(request);
QEventLoop loop;

connect(srequest, SIGNAL(finished()), Sloop, SLOT(quit()));


loop.exec();
}


, ,
, -.
, ,
, , ,
- . -
QNetworkProxy. 39.34.

39.34. -

QNetworkProxy proxy;
proxy.setType(QNetworkProxy::HttpProxy);
proxy.setHostName("192.168.178.1");
proxy.setPort(8080);
586 VI. Qt

proxy.setUser("user");
proxy.setPassword("password" );
QNetworkProxy::setApplicationProxy(proxy);

39.34 QNetworkProxy , 1-,


, -.
setApplicationProxy ( ) .

TCP UDP.
, ,
. , UDP
( ),
, TCP.

. : .
- :
, ,
. ,
. .
Qt
QNetworkAccessManager.
40

XML


, - ,
,
.

XML (Extensible Markup Language,


) . , ,
, , XML.

. XML.
XML 1996 , 1998 W3C (World
Wide Web Consortium) . , XML
SGML,
1 980-. XML HTML
, SGML, , ,
, .
XML ,
. XML
, XML. XML-
ASCII Unicode, .
XML-
, Notepad () Windows.


XML-
XML .
: , ,
. . XML HTML. XML
. , , , XML
, HTML, , XML ,
XML-, .

.
588 VI. Qt

XML-,
, , ,
:

<?xml version = "1.0"?>


<! Address Book >
<addressbook>
<contact number = "1">
<name>Piggy</name>
<phone>+49 631322187</phone>
<email>piggy@mega.de</email>
</contact>
<contact number = "2">
<name>Kermit</name>
<phone>+49 63132218l</phone>
<email>kermit@mega.de</email>
</contact>
</addressbook>

XML- ,
. XML-
(elements). < >, .
.
: <name>, , : </name>.
: <name>Piggy</name>,
. , , :
<empty></empty>. XML
, : <empty/>. ,
,
, , : <empty
number = "l"x/empty> <empty number = "i"/>. ,
.
XML- ,

, < ! >.
HTML XML :
,
, . , XML <>
, HTML, , ,
properties ();


. , , ,
: <Tagx/Tag> <tagx/tag> .
. 40.1 XML. ,
XML- .
40. XML 589

I [.]
version =1.0"
My Address Book

___
addressbook

(number ="1)
name

__ I
phone
.Piggy

I
j_ _- fTFXTt
- +49631322187
email

-
I [TEXT| piggy@mega.de

. 40.1. XML-

XML Qt
Qt XML. , Qt Designer
(. 44) .
Qt,
(. 30).
XML Qt Qtxml,
.

:
QT += xml

,
QtXml:
tinclude <QtXml>

Qt XML. DOM,
SAX, QXmlstreamReader. ,
, .

DOM
DOM (Document Object Model, )
API
XML-, W3C. Qt
, W3C
(name spaces). DOM
XML- .
. ,
, , DOM
.
590 VI. Qt

. 40.2. DOM
QDomNode

QDomCharacterData

QDomText
2
|j3DomDSectiorJ
. 40.2 QDomNode,
Qt DOM.
|QDomComment J
DOM ( QDomAttr

QtXml.
: QDomNode, QDomElement, QDomAttr
|QDomDocument J
QDomText. |QDomDocumentFragment

XML-
QDomDocumentType _)
QDomElement 2 QDomElement

. DOM |QDomEntity
. ,
. , QDomEntityReference
, ,
QDomElement.
QDomNotation
2
DOM QDomNode, JDomPracessinglnstmctionJ
.
, , ,
. QDomNode
QDomElement QDomNode::toEiement () .

( isNuii()).
, 40.1 40.2, XML-
:
Attr: "1"
TagName: "name" Text : "Piggy"
TagName: "phone" Text : "+49 631322187
TagName: "email Text: "piggy@mega.de"
Attr: "2"
TagName: "name" Text: "Kermit"
TagName: "phone" Text: "+49 631322181"
TagName: "email" Text: "kermit@mega.de
XML Qt ,
QT pro- ( 40.1).
CONFIG, console. ,
Windows.

40.1. XmlDOMRead.pro

TEMPLATE = app
QT += xml
40. XML 591

Win32: CONFIG += console


SOURCES = main.cpp
TARGET = ../XmlDOMRead
main(), 40.2, QDomDocument
QFile. QDomDocument XML-.
XML- setContextO QDomDocument
, , QiODevice.
QFile. , QDomElement
documentElement ( ) QDomDocument, XML-
. traverseNode ( ),
XML-.
DOM .
traverseNode ( ) firstChild ( ) nextSibling ( ) QDomNode.
nextSibling ( ) , ,
. isElement ( ) .
, QDomElement
toElement ( ) QDomElement.
"contact" ( tagNameO) attribute ()
number.
tagName ( ) text ( ) .

40.2. main.cpp

# include <QtXml>
//
void traverseNode(const QDomNodes node)
{
QDomNode domNode = node.firstChild ();
while (! domNode.isNull()) {
if(domNode.isElement ()) {
QDomElement domElement = domNode.t oElement ();
if ( ! domElement.isNull ( )) {
if(domElement .tagName () == "contact") {
qDebugO "Attr: "
domElement.attribute("number", "");
}
else {
qDebugO "TagName: " domElement .tagName ()
"\tText: " domElement .text ();
}
}
}
traverseNode(domNode);
domNode = domNode.nextSibling ();
592 VI. Qt

//
int main()
{
QDomDocument domDoc;
QFile file("addressbook.xml");

if(file.open(QIODevice::Readonly)) {
if(domDoc.setContent(&file)) {
QDomElement domElement= domDoc.documentElement();
traverseNode(domElement);
}
file.close();
}

return 0;
}

XML-
XML-
. QDomDocument :
createElement(), createTextNode(), createAttribute ( ) .
.
, 40.3, XML-
. QDomDocument
, .
"addressbook". appendChild( )
. contact ( ) ,
(. 40.4). appendChildO
domElement. XML-
tostring ( ) , XML-,
.

40.3. main.cpp. maln()

int main()
{
QDomDocument doc("addressbook");
QDomElement domElement = doc.createElement("addressbook");
doc.appendChild(domElement);

QDomElement contact1 =
contact(doc, "Piggy", "+49 631322187", "piggy@mega.de");

QDomElement contact2 =
contact(doc, "Kermit", "+49 631322181", "kermit@mega.de");

QDomElement contact3 =
contact(doc, "Gonzo", "+49 631322186", "gonzo@mega.de");
40. XML 593

domElement.appendChiId(contact1);
domElement.appendChiId(contact2);
domElement.appendChild(contact3);

QFile file("addressbook.xml");
if(file.open(QIODevice::WriteOnly)) {
QTextStream(sfile) doc.toString();
file.close();
}
return 0;
}

40.4 contact(). ,
.
.
makeElement ( ) , ,
.

40.4. main.cpp. contact ()

QDomElement contact( QDomDocuments domDoc,


const QStrings strName,
const QStrings strPhone,
const QStrings strEmail

{
static int nNumber = 1;

QDomElement domElement = makeElement(domDoc,


"contact",
QStringO .setNum(nNumber)
);
domElement.appendChild(makeElement(domDoc, "name", "", strName));
domElement.appendChild(makeElement(domDoc, "phone", "", strPhone));
domElement.appendChild(makeElement(domDoc, "email", "", strEmail));

nNumber++;

return domElement;
}

40.5 makeElement () ,
createElement ( ) QDomDocument.
, number.
createAttribute ( ) QDomDocument.
setvalue ( ) .
, createTextNode ( )
QDomNode . appendChild ( )
.
594 VI. Qt

40.5. main.cpp. makeElementO

QDomElement makeElement( QDomDocument& domDoc,


const QStrings strName,
const QStrings strAttr = QString(),
const QStrings strText = QString()
)
{
QDomElement domElement = domDoc.createElement(strName);

if (!strAttr.isEmpty()) {
QDomAttr domAttr = domDoc.createAttribute("number");
domAttr.setValue(strAttr);
domElement.setAttributeNode(domAttr);
}

if (!strText.isEmpty()) {
QDomText domText = domDoc.createTextNode(strText);
domElement.appendChild(domText);
}
return domElement;
}

c SAX
DOM
. XML- SAX.
SAX (Simple API for XML, API XML) Java API
XML-. SAX XML-
, .

XML-
QXmlSimpieReader XML-, SAX.
XML- , ,
. :
, XML-. ,
, XML-.
SAX . 40.3. QXmlContentHandler
QXmlSimpieReader. ,
QXmlEntityResolver, QXmlDTDHandler, QXmlErrorHandler, QXmlDeclHandler
QxmlLexicaiHandier, ,
XML-.
, XML-
: QXmlContentHandler QXmlErrorHandler. QXmlContentHandler
, .
:
40. XML 595

1. startDocument ( ) XML-.
2. startElement ( ) .
3. characters() .
4. endElement ( ) .
5. endDocument ( ) .

|QXmlContentHandler |
j QXmlDTDHandler |

|QXmlDedHandlgi
. 40.3.
[ QXmlEntityResolver | SAX

[ 11
| QXmlLexicalHandler |

fQXmlDefaultHandleJ
QXmlDefaultHandler,
(. . 40.3).
. XML-
: startDocument(), startElement(), characters!), endElement(), endDocument ( )
fataiError () . QXmlErrorHandier.
true,
QXmisimpieReader , . false
, ,
errorstring().
, 40.6 40.7, XML-.
, 40.1 40.2.
, 40.6,
AddressBookParser (. 40.7), QFile ( ) QXmisimpieReader
( ). XML- SAX-,
QXmlinputSource, QiODevice.
parse!) QXmisimpieReader.
XML-.
setContentHandler , QXmlContentHandler,
XML- .

40.6. main.cpp. main()

int main()
{
AddressBookParser handler;
QFile file("addressbook.xml");
QXmlinputSource source(sfile);
QXmisimpieReader reader;
596 VI. Qt

reader.setContentHandler( shandler);
reader.parse(source);

return 0;
}

40.7 AddressBookParser ,
XML-.
startEiement( ) endEiement ( ) ,
, . startEiement()
, . ,
, XML,
, , , ,
.
number, . characters!)
m strText. ,
AddressBookParser.
endEiement , .
, , . contact
addressbook, . fatalError( )
, XML-.
XML-
, , .

40.7. main.cpp. AddressBookParser

class AddressBookParser : public QXmlDefaultHandler {


private:
QString m_strText;

public:
//
bool startEiement(const QStrings,
const QStrings,
const QStrings,
const QXmlAttributess attrs
)
{
for(int i = 0; i < attrs.count(); i++) {
if(attrs.localName(i) == "number") {
qDebugO "Attr:" attrs.value(i);
)
}
return true;
}

//
bool characters(const QStrings strText)
(
m strText = strText;
40. XML 597

return true;
}

//
bool endElement(const QStrings, const QStrings, const QStrings str)
{

if (str != "contact" && str != "addressbook") {


qDebug() "TagName:" str
"\tText:" m strText;

return true;
}

//
bool fatalError(const QXmlParseExceptions exception)
{
qDebug() "Line:" exception.lineNumber()
", Column:" exception.columnNumber()
", Message:" exception.message();
return false;
}

QXmlStreamReader XML
Qt XML-
QXmlStreamReader. SAX,
, , SAX.
SAX.
QXmlStreamReader 40.8.

40.8. main.cpp. QXmlStreamReader

#include <QtXml>

int main()
{
QFile file("addressbook.xml");
if(file.open(QIODevice::Readonly)) {
QXmlStreamReader sr(sfile);
do {
sr.readNext();
qDebug() sr.tokenstring() sr.nameO sr.textO;
} while(!sr.atEnd());

if (sr.hasError()) {
qDebug() "Error:" sr.errorstring();
}
598 VI. Qt

file.close();

return 0;

40.8 XML- addressbook.xml


.
QXmlStreamReader sr. readNextO do...while
, .
( tokenstring ( ) ), ( ())
( text ( ) ). ,
( atEnd()).

hasError ( )
( errorstring ()).
:
StartDocument" "" ""
Comment" "" " My Address Book
StartElement" "addressbook" ""
Characters" ii
StartElement" "contact" ""
Characters"
StartElement" "name" ""
Characters" "" "Piggy"
EndElement" "name" ""
Characters" II II II
StartElement" "phone" ""
Characters" "" "+49 631322187"
EndElement" "phone" ""
Characters" II II II
StartElement" "email" ""
Characters" mi "piggy@mega.de"
EndElement" "email ""
Characters" II II II
EndElement" "contact" ""
Characters" II II II
StartElement" "contact" ""
Characters" II
StartElement" "name" ""
Characters" "" "Kermit"
EndElement" "name" ""
Characters" II II II
StartElement" "phone" ""
Characters" "" "+49 631322181"
EndElement" "phone" ""
Characters" II II II
StartElement" "email" ""
Characters" "" "kermit@mega.de
40. XML 599

"EndElement" 'email'
"Characters" I II II II
"EndElement" contact" ""
"Characters" I II II
"EndElement" 'addressbook" ""
"EndDocument " II II II II

XQuery
XQuery (XML Query Language, XML) ,
XML- .
, XSLT, SQL . Qt
XQuery QXmlQuery,
QtxmlPatterns. XQuery
( 40.9).
pro-. QtxmlPatterns
:
QT += xmlpatterns

40.9 ,
: , XML-, XQ- XQuery.
.
strQuery XQ-,
( 2). XML- ( xmlFile)
, , QXmlQuery.
XQuery- XML-,
inputDocument QXmlQuery: :bindVariable ( ) .

QXmlQuery: :setQuery() ,
XQ-, QXmlQuery: : isvalid ( ) .
QXmlQuery: : evaluateTo ( )
Qstring, .
,
qDebug ( ) .

40.9. main.cpp. XQuery

# include <QtCore>
# include <QtXmlPatterns>

int main(int argc, char** argv)


{
QCoreApplication app(argc, argv);
if (argc < 3) {
qDebug ( ) "usage: XQuery any. xml any.xq";
return 0;
}
QString strQuery =
QFile xqFile (argv[2] ) ;
600 VI. Qt

if(xqFile.open(QIODevice::Readonly)) {
strQuery = xqFile.readAll();
xqFile.close();
}
else (
qDebugO "Can't open the file for reading:" argv[l];
return 0;
}

QFile xmlFile(argv[1]);
if(xmlFile.open(QIODevice::ReadOnly)) {
QXmlQuery query;
query.bindVariable("inputDocument", sxmlFile);
query.setQuery(strQuery);
if (!query.isValidO ) {
qDebugO "The query is invalid";
return 0;
}

QString strOutput;
if (!query.evaluateTo(sstrOutput)) {
qDebugO "Can't evaluate the query";
return 0;
}

xmlFile.close();
qDebugO strOutput;

return app.exec();
)

, 40.10, XML-.
XML- declare
variable. external ,
, .
"/addressbook/contact/"
concat() .

40.10. _all.xq.

declare variable $inputDocument external;


doc($inputDocument)/addressbook/contact/
concat('(name:' , name, ' email:', email, ' phone:', phone, ') ')

(name:Kermit email:kermit@mega.de phone:+49 631322181)

:
XQuery addressbook.xml _all.xq
40. XML 601

:
(name:Piggy email:piggy@mega.de phone:+49 631322187)

40.1 1 ,
for, where, order by return.
SELECT FROM WHERE SQL.

40.11. _kermit.xq.

declare variable $inputDocument external;


for $x in doc( $inputDocument)/addressbook/contact/name
where data($x) = "Kermit"
order by $x
return data($x)

40.1 1 for ,
, "/addressbook/contact/name". where

, "Kermit".
order by ( ,
). return ,
.
:
XQuery addressbook.xml _kermit.xq
:
"Kermit"

40.2 , . ,
number 1.
concat().

40.12. _piggy.xq.

declare variable $inputDocument external;


doc($inputDocument)/addressbook/contact[xs:integer(Snumber) = 1]/
concat(name, '; email, '; ', phone)

:
XQuery addressbook.xml _piggy.xq

:
"Piggy; piggy@mega.de; +49 631322187"

XML- .
,
, :
doc($inputDocument)/addressbook/contact[xs:integer(Snumber) < 20 and @land =
"Germany"]/.
602 VI. Qt


20.

. "addressbook" ,
. :
doc($inputDocument)/addressbook[@owner = "Max Schlee"]/contact/.
,
Max Schlee.
, , :
empty!) true, , count!),
. 40.13 count!)
, XML-.

40.13. _count.xq.

declare variable $inputDocument external;


count(doc($inputDocument)//contact)
:
XQuery addressbook.xml _count.xq
:
"2"


XML. XML
.
Qt XML-: DOM, SAX
QXmlStreamReader. XML- (
), .
XML- .
, .
, SAX
,
. ,
. ,
XML-, SAX .
XQuery Qt Qtxml Patterns.
XML-,
. SQL .
QtXmlPatterns.
41

,
, ... .

, .
,
. (. 41.1).
, / .
, , , .
,
, .

_

.



_
1
| number name phone
1 email

1
()_
TJ1_ Kermit
Piggy +49 631322187 piggy@mega.de
+49 631322181 kermit@mega.de

( )
(;
() _ Gonzo +49 631322186 gonzo@mega.de


() ()

. 41.1. ()

: ,
, . .
SQL (Structured Query Language, ),
,
.

SQL
, , :
, ( ), , .
, SQL, . -
604 VI. Qt

SQL ,
, ( ),

. ,
,
.
, SQL , ,
, . , SELECT, select, Select . .
SQL . SQL
.


, . 41.1, CREATE TABLE,
, , :
CREATE TABLE addressbook (
number INTEGER PRIMARY KEY NOT NULL,
name VARCHAR(15),
phone VARCHAR( 12),
email VARCHAR(15)
);


. SQL
INSERT INTO.
, .
VALUES:
INSERT INTO addressbook (number, name, phone, email)
VALUES(1, 'Piggy', '+49 631322187', 'piggy@mega.de');

INSERT INTO addressbook (number, name, phone, email)


VALUES(2, 'Hermit', '+49 631322181', 'kermit@mega.de');


SELECT ... FROM ... WHERE
. , .
.
:
1. SELECT
, . SELECT
*, ,
.
.
2. FROM , .
41. 605

3. WHERE .
, . ,
.
, Piggy :
SELECT email
FROM addressbook
WHERE name = ' Piggy';


UPDATE ... SET ... WHERE.
SET ,
, = .
, .
, , WHERE.
Piggy
piggy@mega.de piggy@supermega.de:
UPDATE addressbook
SET email = 'piggy@supermega.de'
WHERE name = ' Piggy';

DELETE FROM ... WHERE.


WHERE ,
. , Piggy :
DELETE FROM addressbook
WHERE name = 'Piggy';

SQL Qt
Qt QtSql.
, :
QT += sql
,
QtSql:
#include <QtSql>

QtSql :
1. .
2. .
3. .
.
, QSqlDriver, QSqlDriverCreator<T*>, QSqlDriverCreatorBase,
QSqlDriverPlugin QSqlResult.
606 VI. Qt


. : QSqlDatabase, QSqlQuery,
QSqlError, QSqlField, QSqllndex QSqlRecord.

. : QSqlQueryModel, QSqlTableModel
QSqlRelationalTableModel.
,
.
, Qt.
, , Qt, . 41.1.
( SQLite) -,

. ,
SQLite, ,
Qt.

41.1.

QOCI Oracle Oracle Call Interface (OCI).


7, 8 9
QODBC ODBC (Open Database Connectivity,
) ODBC- Microsoft SQL Server, IBM DB2, Sybase
SQL, iODBC
QMYSQL MySQL
.
www.mysql.com

QTDS Sybase Adaptive Server


QPSQL PosgreSQL SQL92/SQL3
QSQLITE2 SQLite 2
QSQLITE SQLite 3
QIBASE Borland InterBase
QDB2 DB/2 , IBM

. 41.1 ,
.
Qt ,
(plug-ins).
.
Qt ,
, ,
configure
-I -L
. , -piugin-sql-
: db2, ibase, mysql, oci, odbc, psql, sqlite, sqlite2 tbs. , MySQL
:
41. 607

Windows:
configure -plugin-sql-mysql -I C:\mysql\include -L C:\mysql\lib

Linux:
configure -plugin-sql-mysql -I/urs/local/mysql/include -L/urs/local/mysql/lib


,
Qtsqi,
-plugin-sql- -qt-sql-.

,
, . Qt (src),
qtbase/src/plugins/sqldrivers.
. , PostgreSQL
psql. , :
Windows:
qmake "INCLUDE +=:/psql/include LIBS+=C:/psql/libpq.a"

Linux:
qmake "INCLUDE PATH+=/usr/ include/pgsql LIBS+=-LC:/usr/lib -lpg"


MinGW,
reimp. , Windows
*.//,
Microsoft. MSYS MinGW.

!

, ,
. , Windows
<MyApplication>/sq!drivers/. Linux
, Mac OS X macdeployqt,
.
, . ,
, .

( )
.
QSqlDatabase::addDatabase () ( 41.1).
, (. . 41.1).

41.1. main.cpp.

static bool createConnection ()


{
QSqlDatabase db = QSqlDatabase::addDatabase ("QSQLITE");
db.setDatabaseName ( "addressbook");
608 VI. Qt

db. setUserName ( "elton" ) ;


db.setHostName ("epica") ;
.
db setPassword ( "password" ) ;
if ( idb.open ( ) ) {
qDebugO "Cannot open database:" db. lastError () ;
return false;
}
return true;
}

, :

QSqlDatabase : : setDatabaseName ( ) ;
, ,
QSqlDatabase : : setUserName ( ) ;

, ,
QSqlDatabase : : setHostName ( ) ;

QSqlDatabase : : setPassword ( ) .
,
(. 41.1).
QSqlDatabase : : addDatabase ( )

QSqlDatabase: :() . ,
, . ,
QSqlDatabase : : lastError ( ) ,
QSqlError. qDebug ( ) .
, text ( )
QSqlError .
QSqlDatabase

, .
. QSqlDatabase: : tables ()
,
:
QStringList 1st = db. tables ();
foreach (QString str, 1st) {
qDebugO "Table:" str;
}

SQL ( )
SQL
QSqlQuery. () ,
QSqlQuery: :().
.
QSqlQuery . ,
SELECT next ( ) ,
previous (), first (), last ( ) seek(). next()
, previous ( )
. first () last()
41. 609

. seek ( ) ,
.
size().
INSERT. ,
. : prepare ()
bindvalue ( ) . prepare ( ) ,
bindvalue(). :
query.prepare("INSERT INTO addressbook (number, name, phone, email)"
"VALUES(:number, :name, :phone, :emai1);");
query.bindvalue(" inumber", 1);
query.bindvalue(":name", "Piggy");
query.bindvalue(":phone", "+49 631322187");
query.bindvalue(":email", "piggy@mega.de");
ODBC
:
query.prepare("INSERT INTO addressbook (number, name, phone, email)"
"VALUES(?, ?, ?, ?);");
query.bindvalue(1);
query.bindvalue("Piggy");
query.bindvalue ("+49 631322187");
query.bindvalue("piggy@mega.de");
QString, ,
QString::arg ( ) ,
. 41.2.
,
, ,
, .
, 41.2, SQL.
, . ,
:
1 "Piggy" ; "+49 631322187" ; "piggy@mega.de"
2 "Kermit" ; "+49 631322181" ; "kermit@mega.de"

41.2. SQL. main.cpp. man()

int main(int argc, char** argv)


{
QCoreApplication app(argc, argv);

//
if (!createConnection()) {
return -1;
}

//
QSqlQuery query;
610 VI. Qt

QString str = "CREATE TABLE addressbook ( "


"number INTEGER PRIMARY KEY NOT NULL, "
"name VARCHAR(15), "
"phone VARCHAR(12), "
"email VARCHAR(15) "
ii . .
\
)r f

if (!query.exec(str)) {
qDebugO "Unable to create a table";
}

//
QString strF =
"INSERT INTO addressbook (number, name, phone, email) "
"VALUES(%1, '%2', * %3, '%4');";

str = strF.arg("1)
.arg("Piggy")
.arg("+49 631322187")
.arg("piggy@mega.de");
if (!query.exec(str)) {
qDebugO "Unable to make insert operation";
}

str = strF.arg("2")
.arg("Kermit")
.arg("+49 631322181")
.arg("kermit@mega.de");
if (!query.exec(str)) {
qDebugO "Unable to make insert operation";
}

if (!query.exec("SELECT * FROM addressbook;")) {


qDebugO "Unable to execute query - exiting";
return 1;
}

//
QSqlRecord rec = query.record();
int nNumber = 0;
QString strName;
QString strPhone;
QString strEmail;

while (query.next()) {
nNumber = query.value(rec.indexOf("number")).tolnt();
strName = query.value(rec.indexOf("name")).toString();
strPhone = query.value(rec.indexOf("phone")).toString();
strEmail = query.value(rec.indexOf("email")).toString();
41. 611

qDebugO nNumber " " strName ";\t"


strPhone ";\t" strEmail;
}

return 0;
}

createConnection ( )
41.2 , SQL .
( ) QSqiQuery. ,
. ,
, strF
INSERT. arg() QString
, .
, , ,
SELECT, query.
. next < )
.
. , , next ( )
false, .
QSqiQuery::value(),
. record ( ) .
QSqlRecord,
SELECT . QSqlRecord::indexOf(), .
value ( ) QVariant. QVariant ,
(. 4).
,
QVariant : :tolnt ( ) QVariant ::toString ( ) .
QSqlRecord. , 41.2
, - ,
. , , ,
, QSqlRecord: : count
QSqlRecord::fieldName() ,
.
, QSqlRecord: : field ( ) .
QSqlField,
, , , ( QSqlField: : ), ( QSqlField::
type ( ) ), ( QSqlField: : length ) ( QSqlField: : valued).

QSqlRecord::contains().

SQL- ( )
QtSqi (. 12),
.
.
. Qt
612 VI. Qt

: , .
.


-
SELECT, QSqlQueryModel.
,
.
41.3
Piggy.
(. 41.2).

. 41.2.

41.3 QTableView
QSqlQueryModel. setQueryO,
if
lastError ( ) . QSqlError, , ,
, . isValidO.
qDebug ( ) .
setModel ( ).

41.3. . main.cpp. mainQ

int main(int argc, char** argv)


{
QApplication app(argc, argv);

if ( ! createConnection ()) {
return -1;
}

QTableView view;
QSqlQueryModel model;
mode l.setQuery("SELECT phone, email "
"FROM addressbook "
"WHERE name = 'Piggy';"
);

if (model.lastError().isValid() ) {
qDebug () model.lastError ( );
41. 613

view.setModel(smodel);
view.show();
return app.exec();
}


QSqiTabieModei
QSqlQueryModei. ,
. ,
.
,
, removeColumn ( ) .
( 41 .4), . 41.3,
.

_ SQLTableModel [ CZ,
I 0 \r-Z3
number name phone email

1 1 Piggy HS3 31322187 piggy@mega.de

2 2 Kermit -*49 631322181 kermit@mega.de

. 41.3.

41.4 ,
createConnection ( ) (. 41.1 ),
QTableView QSqiTabieModei. setTableO
. select ( )
.

41.4. . main.cpp. mainQ

int main(int argc, char** argv)


{
QApplication app(argc, argv);

if (!createConnection()) {
return -1;
}

QTableView view;
QSqiTabieModei model;

model.setTable("addressbook");
model.select();
model.setEditStrategy(QSqiTabieModei::OnFieldChange);

view.setModel(smodel);
view.show();

return app.exec();
614 VI. Qt

.
QSqlTableModel ,
setEditStrategy ( ) :
OnRowChange ,
;
OnFieldChange ,
;
OnManualSubmit submitAll () .
revertAll{), .
, . 41.3
QSqlTableModel::OnFieldChange, setEditStrategy ( )
.
. setModel { ) .


rowCount ( ) .
, , .
for (int nRow = 0; nRow < model.rowCount(); ++nRow) {
QSqlRecord rec = model.record(nRow);
int nNumber = record.value("number").tolnt();
QString strName = record.value("name").toStringO ;



. setFilterO,
, SQL-WHERE. setSort ( )
.
:
model.setFilter("name = 'Piggy'");
model.setSort(0, Qt::DescendingOrder);
model.select();


, insertRow( ) ,
, ,
setDataO . ,
OnFieldChange OnRowChange
. , :
model.insertRows(0, 1);
model.setData(model.index(0, 0), 4);
model.setData(model.index(0, 1), "Sam");
model.setData(model.index(0, 2), "+49 63145476576");
model.setData(model.index(0, 3), "sam@mega.de");
41. 615

if (!model, submit All () ) {


qDebugO "Insertion error!";
}


,
, removeRows ( ) . ,
Piggy :
.
model setFilter ( "name = 1 Piggy ' " ) ;
model . select ( ) ;
model . removeRows ( 0 , model . rowCount ( ) ) ;
model . submitAll ( ) ;


, ,
.
(primary) / (foreign keys).
.
Qt QSqlRelationalTableModel.
QSqlTableModel.
, :
relationModel ( ) , relation ( ) setRelation ( ) .
"addressbook" "status",
, / .
CREATE TABLE status (
number INTEGER PRIMARY KEY NOT NULL,
married VARCHAR ( 5 ) "
);

:
INSERT INTO status (number, married) VALUES(1, YES');
INSERT INTO status (number, married) VALUES (2, 'NO');

( 41.5) ,
. 41.4.

7 )
'I SqlRelationalTableModel

married name phone email


L jYES i P'sigy +49 631322187 piggy@me<|a,cle

2 NO Kermit +49 631322181 kermit@meqa.de

. 41.4.

41.5 41.3 setRelation () .


"addressbook",
. QSqlRelation.
616 VI. Qt

"status", "addressbook",
"status" ,
.

41.5. . main.cpp. mainQ

int main(int argc, char** argv)


{
QApplication app(argc, argv);

if (!createConnection()) {
return -1;
}

QTableView view;
QSqlRelationalTableModel model;

model.setTable("addressbook");
model.setRelation(0, QSqlRelation("status", "number", "married"));
model.select();

view.setModel( smodel);
view.show();

return app.exec();
}

.
.
, Qt .
, , ,
: , . .
SQL
, ,
. ()
, , .
Qt , :
, .
,
. SQL , ,
. QSqlQuery.
SQL-
.
42



, .

,
.
, .
Qt (plug-ins).


, ,
- ,
. ,
, ,
(),
.
.
( )
, .
:
.
,
, ;
, ;

, ,
. ,
, .
,
, .
, ,
. ,
,
, - .
618 VI. Qt

, (
pro), :
TEMPLATE = lib
CONFIG += dll

: TEMPLATE , ,
, , .
: CONFIG, ,
. , ,
. Windows dll, Mac OS X
dylib, Linux so.

, .
, Tools. pro-
, . :
LIBS
+= -L../../lib/ ITools
INCLUDEPATH = ../../include
, Tools ,
,
, .

. ,
PATH. , :
Windows:
set =%%;:\Projects\cpp\lib\win32

Mac OS X:
export DYLD_LIBRARY_PATH=/Projects/cpp/lib/mac/:$DYLD_LIBRARY_PATH

Linux:
export LD_LIBRARY_PATH=/Projeets/epp/lib/xll/:$LD_LIBRARY_PATH
, , Windows

. Mac OS X macdeployqt. Linux
, LD_LIBRARY_PATH.


.

.
. .
.

. , , ,

42. 619

.
QLibrary. ,
.

!
, ,
.

, 42.1 2.3,
, .
, 42.1.
TEMPLATE lib.
,
DESTDIR " . .".
,
, , , -=
gui QT.

42.1. dynlib.pro

TEMPLATE = lib
DESTDIR = ..
QT -= gui
SOURCES = dynlib.cpp
HEADERS = dynlib.h
TARGET = dynlib


( 41.2).
extern "C++" C++
.
oddUpper ( ) ,
. ,
,
, , QLibrary, .


C++ ,
. "C++" .

42.2. dynlib.h

#include <QString>
extern "C++" {
QString oddUpper(const QStrings str);
}

42.3 ,
.
620 VI. Qt

42.3. dynlib.cpp

#include "dynlib.h"

QString oddUpper(const QStrings str)


(
QString strTemp;

for (int i = 0; i < str.length(); ++i) {


strTemp += (i % 2) ? str.at(i) : str.at(i).toUpper();
}

return strTemp;
)

, 42.4,
, .
(. 42.1).

1-:
.This iS ThE ExAmPIE Te)4

. 42.1.

42.4 1,
. ,
QLibrary , ,
, , . ,
. ,
Windows dll, UNIX/Linux so,
OS X dylib. , Qt
.
resolved.
,
. void,
. resolve ( ) , ,
. .
.
show().

42.4. main.cpp

#include <QtWidgets>

int main(int arge, char** argv)


{
QApplication app(argc, argv);
QLabel lbl("this is the example text");
QLibrary lib("dynlib");
42. 621

typedef QString (*Fct) (const QStrings);


Fct fct = (Fct)(lib.resolve("oddUpper"));
if (fct) {
1.setText(fct(1.text()));
}
1.show();

return app.exec( );
)

(plug-ins)

. , ,
,
.
:
Qt;
.

Qt
Qt ,
, , ,
. . 20-. :
QSqiDriverPlugin ;
QPictureFormatPlugin, QlmagelOPlugin
(. 79);
QTextCodecPlugin ;
QStylePlugin (. 26).
QObject,
Qt. Qt ,
. QStylePlugin.
, 26 CustomStyle,
, 42.5 2.7.
, QStylePlugin ( 42.5),
create . Qt,
, Q_PLUGIN_
METADATA. IID ,
, JSON (.
50). , ,
, .

42.5. CustomStylePlugin.h. CustomstylePlugin

class CustomStylePlugin : public QStylePlugin{


Q OBJECT
622 VI. Qt

Q_PLUGIN_METADATA(IID, "com.mycorp.Qt.Customlnterface" FILE mystyleplugin.json)


public:
QStyle* create(const QString &key);
};

JSON- mystyleplugin.json, 42.6,


. : CustomStyle MyStyle.

42.6. mystyleplugin.json

{
"Keys": ["CustomStyle", "MyStyle"]
}

create ( ) .
, ( 42.7).

42.7. CustomStylePlugin.cpp. create

QStyle* MyStylePlugin::create(const QString &key)


{
if (key == "CustomStyle")
return new CustomStyle;
if (key == "MyStyle")
return new MyStyle;
return 0;

.
QStyleFactory ( 42.8).

42.8. main.cpp

void main(int argc, char** argv)


{

QApplication::setStyle(QStyleFactory::create("CustomStyle"));

Qt ,
,
. < Qt>/plugins/styles.

!
Qt
, ,
. , Windows
<MyApplication>/imageformats/
42. 623

<MyApplication>/sqldrivers/ . Linux ,
Mac OS X macdeployqt, .
, ,
Windows, windeployqt. ,
, , WebKit (. 46),
, JPG-, GIF- TIFF-
, .



(. ),

. QPluginLoader,
. instance ( ) ,
. QPluginLoader
, .
, ,
unload ( ) .

( 42.942.14) ,
. , . 42.2,
.

. 42.2. ,

,
( 42.9).
stringinterface, ,
. :
operations ( ) ;
operation ( ) .
, C++
, , ,
.
Q_DECLARE_
INTERFACE ( ) , -, -
.
QPluginLoader ,
624 VI. Qt

. ,
:
;
;
;
.

42.9. interfaces.h

tpragma once

class QString;
class QStringList;

// ==================================
class Stringlnterface {
public:
virtual -Stringlnterface() {}

virtual QStringList operations;) const = 0;

virtual QString operation(const QStrings strText,


const QStrings strOperation
) = 0;
};

Q_DECLARE_INTERFACE(Stringlnterface,
"com.mysoft.Application.Stringlnterface"
)

piuginswindow ( 42.10)
QMainwindow. .

42.10. PluginsWindow.h
#pragma once

#include <QMainWindow.h>
#include "interfaces.h"

class QLabel;
class QMenu;

---
// ===================== ========
class Piuginswindow : public QMainWindow {
Q_OBJECT

private:
QLabel* m_plbl;
QMenu* m_pmnuPlugins;
42. 625

public:
PluginsWindow(QWidget* pwgt = 0) ;

void loadPlugins( );
void addToMenu (QObject* pobj);

protected slots:
void slotStringOperation();
};

, 42.11, .
( m_pibi) , (
m pmnuPiugins) addMenu () .
loadPlugins ( ) .

42.11. PluginsWindow.cpp.

PluginsWindow::PluginsWindow(QWidget* pwgt/*=0*/) : QMainWindow(pwgt)


{
m_plbl = new QLabel("this is the test text");
m_pmnuPlugins = new QMenuC'&PluginsOperations");

loadPlugins();
setCentralWidget(m_plbl);
menuBar()->addMenu(m_pmnuPlugins);
)

.
, plugins,
. QDir ( 42.12)
.
QPluginLoader. , QPluginLoader
instanced, QObject addToMenud,
.

42.12. PluginsWindow.cpp. loadPlugins()

void PluginsWindow::loadPlugins()
{
QDir dir;
if (!dir.cd("plugins" )) {
QMessageBox::critical(0, "plugins directory does not exist");
return;
}

foreach (QString strFileName, dir.entryList(QDir::Files)) {


QPluginLoader loader(dir.absoluteFilePath(strFileName));
addToMenu(qobject_cast<QObject*>(loader.instance()));
626 VI. Qt

addToMenu ( ) ,
( 42.13). , .
, qobjectcast
<stringinterface*>, .
, qobject_
cast<T> .
, , operations!),
lstoperations.
,
, .
siotstringOperation ( ) .

42.13. PluginsWindow.cpp. addToMenu ()

void PluginsWindow::addToMenu(QObject* pobj)


{
if (!pobj) {
return;
}

Stringlnterface* pi = qobject_cast<StringInterface*>(pobj);
if (PD {
QStringList lstoperations = pI->operations();
foreach (QString str, lstoperations) {
QAction* pact = new QAction(str, pobj);
connect(pact, SIGNAL(triggered!)),
this, SLOT(siotstringOperation())
);
m_pmnuPlugins->addAction(pact);

, 42.14, sender () ,
. QAction.
parent ( ) .
operation ( ) , .
,
.

42.14. PluginsWindow.cpp. siotstringOperation()

void PluginsWindow::siotstringOperation()
{
QAction* pact = qobject_cast<QAction*>(sender());

Stringlnterface* pi = qobject_cast<StringInterface*>(pact->parent());

m_plbl->setText(pI->operation(m_plbl->text(), pact->text()));
l
42. 627


, , ,
.
CONFIG pro- plugin,
HEADERS interfaces.h (
42.15).

42.15. MyPlugin.pro

TEMPLATE = lib
CONFIG += plugin
QT -= gui
DESTDIR = ../plugins
SOURCES = MyPlugin.cpp
HEADERS = MyPlugin.h \
../Application/interfaces.h
TARGET = myplugin

MyPlugin, 42.16, :
QObject stringinterface. Q_INTERFACES { ) ,
.
,
Q PLUGIN METADATA( ) , ,
Qt. IID ,
, JSON (. 50).
,
, C++ ,
, , .

42.16. MyPlugin.h

tpragma once

#include <QObject>
#include "../Application/interfaces.h"

// ================================================================
class MyPlugin : public QObject, public Stringinterface {
QjOBJECT
Q_INTERFACES(Stringinterface)
Q_PLUGIN_METADATA(IID "com.mysoft.Application.Stringinterface" FILE
"stringinterface.json")

private:
QString oddUpper(const QStrings str);

public:
virtual -MyPlugin();
628 VI. Qt

virtual QStringList operations( ) const;


virtual QString operation (const QStrings, const QStrings);
};

, 42.17,
. : oddupper lower.

42.17. MyPlugin.cpp. operations()

/virtual*/ QStringList MyPlugin;:operations() const


{
return QStringList() "oddUpper" "lower";
)

oddupper (), 42.18, .


(. 42.3),
.

42.18. MyPlugin.cpp. oddupper()

QString MyPlugin::oddupper(const QStrings str)


{
QString strTemp;

for (int i = 0; i < str.length(); ++i) {


strTemp += (i % 2) ? str.at(i) : str.at(i).toUpper();
1

return strTemp;
}

42.19 operation)), .
, ,
. ,
.

42.19. MyPlugin.cpp. operation()

/virtual*/ QString MyPlugin::operation(const QStrings strText,


const QStrings strOperation
)
{
QString strTemp;
if (strOperation == "oddupper") {
strTemp = oddupper(strText);
1
else if (strOperation = "lower") {
strTemp = strText.toLower();
42. 629

else {
qDebugO "Unsupported operation";
}
return strTemp;

,
. , ,
, , .

, .
,
, .
.

.
, .
Qt
. resolve .
.
, .
Qt :
;
.
Qt
, . ,
.
Qt QPluginLoader,
, . ,
, ,
.
Q_DECLARE_INTERFACE. ,
, ,
, qobject_cast<T>.
,
, .
: QObject , .
Q INTERFACES,
.
Q PLUGIN METADATA ( ) , .
43

Qt
API
.
!
! .

, .
.

.
,

, Qt ,
,
, ,
.
. , ,
.
,

(. 42) .
, ,
, ,
. ,
, :
#if defined(Q_OS_WIN)
// Windows
#elif defined(Q_OS_UNIX)
// UNIX
#elif defined(Q_OS_OSX)
// Mac OS X
#else
//He
#endif

. 43.1 .

,
C++ . : Q_CC_INTEL, Q_CC_MSVC, Q_CC_MINGW,
Q_CC_BR .
43. Qt API 631

43.1.

Q_0S_AIX AIX (Advanced Interactive executive) ,


UNIX System V, IBM
Q_0S_FREEBSD FreeBSD UNIX- ,
UNIX- AT&T
Q_OS_IRIX IRIX UNIX SGI (Silicon Graphics Inc.)
Q_0S_LINUX Linux
, UNIX
Q_S_SX Mac OS X Apple
Macintosh
Q_S_SOLARIS SOLARIS UNIX,
Sun Microsystems
Q_0S_WIN32 32- Windows Microsoft
Q_OS_WIN64 64- Windows Microsoft
Q_OS_IOS iOS, Apple iPhone, iPad
iPod touch
Q_OS_ANDROID Android, Google

Q_0S_WINRT Windows RT Microsoft
Q_0S_WINPH0NE , Microsoft

qmake ,
. pro-
,
,
Mac OS X (frameworks). Mac OS X
mm-, Objective C++.

macx {
DESTDIR = ../../lib/mac
LIBS += -lAnyMacOSXLib -framework AnyFrameworkName
OBJECTIVE_SOURCES += myfile_mac.mm
}
Win32 {
DESTDIR = . ./Iib/win32
LIBS += -lAnyWin32Lib
SOURCE += myfile_win.epp
}
!Win32:!macx {
DESTDIR = ../../lib/xll
LIBS += -lAnyUnixLib
SOURCES += myfile_lin.cpp
}

,
, . ,
:
632 VI. Qt

win32-msvc.net {
SOURCES += MyDotNetFile_win.
}

,
"{)" , ,
Windows :
Win32 : debug: CONFIG += console

qmake 3.

Windows API
( 43.1), . 43.1,
GDI (Graphical Device Interface,
) Windows.
GDI+ DirectX.
Windows API .

. 43.1. GDI

43.1 nativeEvent ( ) .
Qt,
true.
nativeEvent () , QWidget.
, , Windows.
, ,
MessageBoxO Windows API, .

Windows, winid().
, Windows, ,
HWND ( ). HWND.
paintEvent ( )
GDI. ,
QWidget : : ef f ectivewinid ( ) , HWND
Windows API Get DC HDC ( Device
Context, ), GDI,
43. Qt API 633

. (
setAutoFillBackground())
. paintEngine( ),
, ,
.

43.1. main.cpp. WinAPl

class WinAPl : public QWidget {


protected:
virtual bool nativeEvent(const QByteArrayS baType,
void* pmessage,
long* result
)
{
QString strl = "Windows Version = "
+ QString::number(QSysInfo::WindowsVersion);
QString str2 = "Windows Message";

WId id = effectiveWinld();
HWND hWnd = (HWND)id;
MSG* pmsg = reinterpret_cast<MSG*>(pmessage);

switch(pmsg->message) {
case WM_RBUTTONDOWN:
::MessageBox(hWnd,
(const WCHAR*)strl.utf16(),
(const WCHAR*)str2.utf16(),
MB_OK | MB_ICONEXCLAMATION
);
break;
default:
;
}

return QWidget::nativeEvent(baType, pmessage, result);


}

virtual void paintEvent(QPaintEvent*)


{

WId id = effectiveWinld();
HWND hWnd = (HWND)id;
HDC hDC = ::GetDC(hWnd);
HBRUSH hBrush = ::CreateSolidBrush(RGB(255, 0, 255));
HBRUSH hBrushRect = ::CreateSolidBrush(RGB(200, 200, 200));
HPEN hPen = ::CreatePen(PS_SOLID, 2, RGB(0, 0, 128));
QString str = "GDI Drawing";
TEXTMETRIC tm;
634 VI. Qt

: :SelectObject(hDC, hBrushRect);
::Rectangle(hDC, 0, 0, width(), height)));
::GetTextMetrics(hDC, &tm);
;:SelectObject(hDC, hBrush);
;:SelectObject(hDC, hPen);
Ellipse(hDC, 0, 0, width(), height!));
;:TextOut(hDC,
width() / 2 - (tm.tmAveCharWidth * str.length()) / 2,
(height!) - tm.tmHeight) / 2,
(const WCHAR*)str.utf16(),
str.length()
);
::DeleteObject(hBrushRect);
::DeleteObject(hBrush);
::DeleteObject(hPen);
::ReleaseDC(hWnd, hDC);

virtual void resizeEvent(QResizeEvent* pe)


{
update();
QWidget: ; resizeEvent(pe);

public:
WinAPI(QWidget* pwgt = 0) : QWidget(pwgt)
(
setAutoFillBackground(false);
setAttribute(Qt::WA_PaintOnScreen, true);
}

QPaintEngine* paintEngine() const


(
return 0;
}

QString 43.1
(const WCHAR*)str.utfl6 ( ) . 43.2 13.3 ,
, Windows ( . 43.3
, . 43.2).

43.2. QStringe

C++ Standard String std::wstring wstr = qstr.toStdWStringO
BSTR (OLE String) BSTR bstr = ::SysAllocString(qstr.utfl6())
8bit (LPCSTR) LPCSTR lstr = qstr,toLocal8Bit().constData()
43. Qt API 635

43.2 ()


LPCWSTR LPCWSTR wstr = qstr.utfl6()
CString (MFC) CString mfcstr = qstr.utf!6()

43.3. QString


C++ Standard String QString qstr = QString::fromStdWString(wstr)
BSTR (OLE String) QString qstr((QChar*)bstr, wcslen(bstr))
8bit (LPCSTR) QString qstr = QString::fromLocal8Bit(lstr)
LPCWSTR QString qstr = QString::fromUtf16(wstr)
CString (MFC) QString qstr = QString::fromUtf!6((LPCTSTR(mfcstr)))

Linux
Windows, UNIX/Linux Qt
. QWidget xllEventO,
X Window. ,
.
Qt, true.

Mac OS X
Mac OS X
Objectve C++. ,
C++. Objective C++. ,
C++, Objective C++ h-,
C++, , Q_os_osx .
Objective C++ ( Qt)
. -, Objective - ,
,
C++ . C++
Qt ,
. Objective ,
, ,
, , , . .
Qt C++.
Objective ,
, C++,
.
Objective -
, ,
636 VI. Qt

Objective , C++ .
GCC , , Windows
MinGW.
, Objective C++ Objective ,
C++. , C++,
Objective . , Objective
Apple, Mac OS X, iPhone, iPad iPod touch
.

( 43.2 43.7)
() Mac OS X (. 43.2).

0
_
Mac Check Button
A
. 43.2. Mac OS X

pro- ( 43.2) Objective C++


OBJECTIVE SOURCES Cocoa LIBS.

43.2. MacButton.pro

TEMPLATE =
QT += widgets
TARGET = MacButton
macx {
OBJECTIVE_SOURCES += MacButton.mm
LIBS += -framework Cocoa
HEADERS += MacButton.h
}

SOURCES += main.cpp

( 43.3) Q_os_osx ,
( MacButton) ,
Mac OS X.
.

43.3. main.cpp

# include <QtWidgets>
#ifdef Q_OS_OSX

# include "MacButton.h"

#endif
int main(int arge, char** argv)
{
QApplication app(argc, argv);
43. Qt API 637

#ifdef Q_OS_OSX
MacButton cmd;
cmd.show();
#else
QLabel label("This example requires Mac OS X");
label.show();
#endif

return app.exec();
}

( 43.4) ButtonContainer,
QMacCocoaviewContainer,
Mac OS X. qmaccocoaviewcontainer_mac.h,
# import. Objective
# include , ,
h- ,
:
#pragma once

QMacCocoaviewContainer, ,
, MacButton,
ButtonContainer.


,
h-
Q_OS_OSX.

43.4. MacButton.h

#pragma once

#include <QtWidgets>

#import <qmaccocoaviewcontainer_mac.h>

/ / ====================================================
class ButtonContainer : public QMacCocoaviewContainer {
Q_OBJECT
public:
ButtonContainer(QWidget* pwgt = 0);

QSize sizeHintO const;


};

/ / ===============================
class MacButton : public QWidget {
Q OBJECT
638 VI. Qt

public:
MacButton(QWidget* pwgt = 0);
};

( 43.5)
Objective . Cocoa ,
( NSButton) .
Objective alloc,
init. alloc
new C++, init
.
( NSButton).
:
setButtonType NSSwitchButton ;
setTitle ;
setState YES ( C++ YES
true) .
( pcmd)
Cocoa setCocoaView ( ).
release ( pcmd)
, , ButtonContainer
.
relase ( ppool).

Objective ,
,
, . , .
, Objective , ,
,
. Objective ,
, , , C++, .

43.5. ButtonContainer.mm. ButtonContainer

ButtonContainer:: ButtonContainer(QWidget* pwgt/*=0*/)


: QMacCocoaViewContainer(0, pwgt)
{
NSAutoreleasePool* ppool = [[NSAutoreleasePool alloc] init];

NSButton* pcmd = [[NSButton alloc] init];

[pcmd setButtonType:NSSwitchButton];
[pcmd setTitle:@"Mac Check Button"];
[pcmd setState:YES];

setCocoaView(pcmd);

[pcmd release];
[ppool release];
43. Qt API 639

sizeHint ( 43.6) ,
.

43.6. ButtonContainer.mm. sizeHint()

QSize ButtonContainer::sizeHint() const


{
return QSize(150, 40);
)

43.7
MacButton.

43.7. ButtonContainer.mm. MacButton

MacButton::MacButton(QWidget* pwgt) :QWidget(pwgt/*=0*/)


{
ButtonContainer* pcmd = new ButtonContainer(this);

QVBoxLayout* pvbx = new QVBoxLayout;


pvbx->setMargin(0);
pvbx->addwidget(pcmd);
setLayout(pvbx);
}

Mac OS X NSString.
NSString QString :
NSString* ns = @"Convert Me To QString";
QString str = QString::fromNSString(ns);

QString NSString,
toNSString(). :
QString str = "Convert Me To NSString";
NSString* ns = str.toNSString();


, ,
, , -
.
, , ,
,
. ,
,
,
.
QSysinfo

:
640 VI. Qt

windowsversion Windows.
: WV_XP, WV_VISTA, WV_WINDOWS7, WV_WIDOWS8_1, - :
WV_CE_5, WV_CE_6 . .;
Macintoshversion Mac OS X,
iOS. : MV_SNOWLEOPARD, MV_LION, MV_MAVERICKS, MV_IOS_6_O, MV_IOS_7_I
. .
,
Linux. ,
Linux.
, Windows, Mac OS X iOS
( 43.8).

43.8.

QString strOSInfo =
#ifdef Q_OS_OSX
int nVer = QSysInfo: imacVersion();
QString strVer = (nVer == QSysInfo::MV_10_5) ? "10.5 Leopard" :
(nVer == QSysInfo::MV_10_6) ? "10.6 Snow Leopard" :
(nVer == QSysInfo::MV_10_7) ? "10.7 Lion" :
(nVer == QSysInfo::MV_10_8) ? "10.8 Mountain Lion" :
(nVer == QSysInfo::MV_10_9) ? "10.9 Mavericks" :
("(" + QString::number(nVer - 2) + ") Unknown");
strOSInfo = "Mac OS X " + strVer;
#elif defined(Q OS WIN)
int nVer = QSysInfo::windowsVersion();
QString strVer = (nVer == QSysInfo::WV 5 0) 9 "2000"
(nVer == QSysInfo::WV_5_1) ? "XP" :
(nVer == QSysInfo::WV_5_2) ? "2003"
(nVer == QSysInfo::WV_6_0) 7 "Vista"
(nVer == QSysInfo::WV_6_1) 7 7 H
(nVer == QSysInfo::WV_6_2) 7 "8" :
(nVer == QSysInfo::WV_6_3) 7 "8.1" :
("(" + QString::number(nVer) + ") Unknown");
strOSInfo = "Win " + strVer;
#elif defined(Q_OS_IOS)
int nVer = QSysInfo::macVersion();
QString strVer = (nVer == QSysInfo::MV_IOS_4_3) ? "4.3"
(nVer == QSysInfo::MV_IOS_5_0) ? "5.0"
(nVer == QSysInfo::MV_IOS_5_l) ? "5.1"
(nVer == QSysInfo::MV_IOS_6_0) ? "6.0"
(nVer == QSysInfo::MV_IOS_6_l) ? "6.1"
(nVer == QSysInfo::MV_IOS_7_0) ? "7.0"
(nVer == QSysInfo::MV_IOS_7_l) ? "7.1"
("(" + QString::number(nVer) + ") Unknown");
strOSInfo = "iOS " + strVer;
#endif
qDebugO "OS and Version strOSInfo;
43. Qt API 641

QSysinfo ,
. , QSysinfo::
ByteOrder. :
if (QSysinfo::ByteOrder == QSysinfo::BigEndian) {
qDebugO "System is big endian";
}
else {
qDebugO "System is little endian";
)

Qt
. ,
, Qt. pro-
,
, .
44

Qt Designer.



...
-

Qt Designer (Rapid Appli


cation Development, RAD). ,
WYSIWYG (What You See Is What You Get,
, ).
, , ,
, . Qt Designer
C++.
, Qt, Qt Designer
, .
Qt Designer
, QLCDNumber.

Qt Designer
Qt Designer (. 44.1) .
: ,
. ., ,
. .
Qt Designer Widget Box (),
, .
.
:
Object Inspector () .
. , Property Editor
( ) ;
Property Editor ( ) .
, , / . .;
Signal/Slot Editor ( )
;
44. Qt Designer. 643

. 44.1. Qt Designer

Resource Editor ( )
;
Action Editor ( ) ,
.
New Form ( )
(. . 44.1).
, Show this Dialog on Startup (
).
File | New Form... ( | ...)
<Ctrl>+<T>.
New Form ( ) .
Widget (), (. 44.2).
Qt Designer
. Qt Designer (. 44.1).

44.1.


Edit Widgets ( ,
) , , ,

644 VI. Qt

44.1 ()

Edit Signals/Slots (
/)

%
Edit Buddies (
) . ,
,

Edit Tab Order ( ,
-
)


. 44.2.

Property Editor ( ) (. 44.3) window Title (


) Form, , DesignedWidget.
object Name ( ) ,
.
MyForm.


ui- uic C++,
,
.
44. Qt Designer. 645

Property Editor a
, , Property Value A

, object Name MyForm


. QWidget
. window Modality Qt:: Non Modal
enabled true
0 geometry 10. 0, 400, 3001
File | Save Form As... ( | 0 size Policy [Preferred. Prefer
...) 0 minimumSize [0,0]
<Ctrl>+<S>. EB maximumSize [16777215, 1677-
r
0 size Increment [0.01
0 baseSize . Pi
palette
0 font p\a [Microsoft S
cursor ATDW
mouseTracking false
focus Policy Qt:: NoFocus
context Menu Policy Qt :: Default Contex _
accept Drops false
windowTitle DesignedWidget +>
window Icon It*
0 toolTip
. 44.3. .

0 statusTip
-

,
Widget Box () (. . 44.2). ,
.
Buttons () PushButton (),
Input Widgets ( )
Horizontal Slider ( ),
Display Widgets ( )
LCDNumber ( )
. ,
, Object Inspector ().
(. 44.4).

Object Inspector (5 x
Object Gass
MyForm QWidget
mjed Q LCD Number
mjDcmdQurt Q Push Button
mjjcmd Reset Q Push Button
m jDsId QSlider

. 44.4. Object Inspector

, Object
Inspector () . text ()
Property Editor ( ) &Reset, object Name ()
646 VI. Qt

m pcmdReset. , object Name ()


m pcmdQuit, text () &Quit. , object
Name (), : ,
. (. . 44.4).
, . 44.5.

. 44.5.

(layout)
, .
, ,
, . .
. ,
. ,
, Lay out | Lay out Vertically (
| )
<Ctrl>+<2>. Reset () Quit ().
, ,
(Spacer). Widget Box () Spacers (
) Vertical Spacer ( )
. ,
. 44.6.
,
.
Dialog Object Inspector ().
Lay out |
Lay out Horizontally ( | )
<Ctrl>+<l>. , . 44.7.

, .
44. Qt Designer. 647

. 44.6.

. 44.7.


.
<> .
,
Edit | Edit Tab Order ( | )
. ,
648 VI. Qt

. 44.8.

. 44.8. ,
, .



, Edit | Edit Signals/Slots (
| /) <F4>.
,
, ,
, .
, .
,
.
Configure Connection
( ),
. valueChanged(int), display(int)
(. 44.9).
Quit (),
closet). ,
, ,
. , . 44.10.
Configure
Connection ( ) clicked ( ) .
close ( ) , Show all signals and slots (
),
.
44. Qt Designer. 649

,
Form | Preview ( | ).
, ,
.
,
, .

. 44.9.

. 44.10.

, .
File | Save Form As... ( |
...), ,
MyFrom.ui.
650 VI. Qt



,
, ui- C++.
:

, QWidget, ,
Promote to.... (. 44.11)
, .
, , ,
,
. ,
Add Promote.

Promoted Widgets
Prnmntf>ri

New Promoted Class

Base class name: QWidget


Add

Promoted class name MySecondWidget| Reset


Header file: mysecondwidget.h

Global include _

Close Promote

. 44.11.


, .
Qt .
(direct approach) . ,
, ui::MyForm: rsetupui ( )
, 44.1.

44.1.

#include "ui_MyForm.h"
#include <QtWidgets>
44. Qt Designer. 651

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


{
QApplication app(argc, argv);

QWidget* form = new QWidget;


Ui::MyForm ui;
ui.setupUi (form);

form->show();

return app.exec();
}


. , , ,
, ,
. ,
, Reset ().
(inheritance approach).
, ,
QWidget ( 44.2).

44.2.

#include "ui_MyForm.h"

class MyForm : public QWidget {


Q_OBJECT
private:
Ui::MyForm m_ui;

public:
MyForm(QWidget* pwgt =0) : QWidget(pwgt)
(
m_ui.setupUi(this);

connect(m_ui.m_cmdReset, SIGNAL(clicked()), SLOT(slotReset()));


}

public slots:
void slotReset()
{
m_ui.m_sld->setValue(0);
m_ui.m_lcd->display(0);
}
};

ui::MyForm
Ui::MyForm::setupUi . Reset
652 VI. Qt

() ( m_cmReset) slotReset ( ) .
, ,
Qt Designer,
. ,
.
,
(multiple inheritance approach).
, ,
. 44.3.

44.3.

# include "ui_MyForm.h"

class MyForm : public QWidget, public Ui::MyForm {


Q_OBJECT

public:
MyForm (QWidget* pwgt = 0) : QWidget (pwgt)
{
setupUi(this);

connect (m_cmdReset, SIGNAL (clicked ()), SLOT (slotReset ()) );


}

public slots:
void slotReset ( )
{
m_sld->setValue(0);
m_lcd->display(0);

# endi f //_MyForm_h_

44.3, MyForm QWidget,


, Qt Designer.

, .

FORMS. , pro-
:
TEMPLATE = app
HEADERS += MyForm.h
FORMS += MyForm.ui
SOURCES += main.cpp
QT += widgets
Win32: TARGET = ../MyForm
44. Qt Designer. 653

, , (MyForm.ui)
, make- :
qmake
make
ui- h- ui_.
,
, . 44.12.

. 44.12.


,
. , XML-
(ui-) , .
QUiLoader, QtuiTools,
,
. QUiLoader
( 44.4 14.6),
44.1 14.3.
( 44.4) QtuiTools
QT. ,
RESOURCES. , FORMS ,
XML- .

44.4. LoadMyForm.pro

TEMPLATE = app
QT += widgets uitools
654 VI. Qt

HEADERS = LoadMyForm.h
SOURCES = main.cpp
RESOURCES = resource.qrc
Win32:TARGET = ../LoadMyForm

, 44.5,
LoadMyForm.

44.5. main.cpp

tinclude <QApplication>
#include "LoadMyForm.h"

int main(int argc, char** argv)


{
QApplication app(argc, argv);
LoadMyForm wgt;

wgt.show();

return app.exec();
}

LoadMyForm QWidget ( 44.6).


QSlider QLCDNumber ,
(m_psld m picd).
QuiLoader ( puil) this.
, QFile
":/MyForm.ui". ioad()
.
, , ,
XML- , .
.
pwgtForm, resized.
,
findChild<TMn*>("" ), QObject.
( m psld), (
m_pcd), Reset ( pcmdReset) Quit ( pcmdQuit).
clicked Reset slotReseto,
.
Quit clicked( ) quit( )
qApp. pwgtForm
LoadMyForm phbxLayout.

44.6. LoadMyForm..

#pragma once

#include <QtWidgets>
#include <QtUiTools>
44. Qt Designer. 655

// =================================================================
class LoadMyForm : public QWidget {
Q_OBJECT
private:
QSlider* m_psld;
QLCDNumber* m_plcd;

public:
LoadMyForm(QWidget* pwgt =0) : QWidget(pwgt )
{
QUiLoader* puil = new QUiLoader(this);
QFile file(":/MyForm.ui");

QWidget* pwgtForm = puil->load(sfile);


if (pwgtForm) {
resize(pwgtForm->size());

m_psld = pwgtForm->findChild<QSlider*>("m_sld");
m_plcd = pwgtForm->findChild<QLCDNumber*>("m_lcd");

QPushButton* pcmdReset =
pwgtForm->findChild<QPushButton*>("m_cmdReset");
connect(pcmdReset, SIGNAL(clicked()), SLOT(slotReset()));

QPushButton* pcmdQuit =
pwgtForm->findChild<QPushButton*>("m_cindQuit");
connect(pcmdQuit, SIGNAL(clicked!)), qApp, SLOT(quit()));

//Layout setup
QHBoxLayout* phbxLayout = new QHBoxLayout;
phbxLayout->addWidget(pwgtForm);
setLayout(phbxLayout);

public slots:
void slotReset()
{
m_psld->setValue(0);
m_plcd->display(0);

};

. Qt Designer
. ,
.
.
656 VI. Qt

. , ,
.
Qt Designer
.
:
;
;
;
ui-.
45

.
. .
:
, ?
?
-.
?
.
?
.
, , ,
!

,
.
.
. , .
, , ,
. , , ,
.
. . ,
,
. ,
, , ,
.
.
, .
, ,
. ,
. ,
, , .
, ,
. ,
, .
, .
. - , -
658 VI. Qt

. ,
,
. ,
,
, .
. , , ,
, .
, .
Qt QtTest,
, .

.
, , (unit tests).

, . ,
, .
(system test),
GUI, , ,
(drag & drop) . ., Squish,
: www.froglogic.com.


.

,
. .
: ,
.
,
. : (25, 0), (-12, -15), (2007,
2007) (-12, 5). , , .
,
. :

Test_.
, MyClass,
Test_MyClass;

() .
45.1 , min
MyClass. QTest.
QObject ,
, QOBJECT.
, private.
QCOMPARE ( ) : ,
. ,
.
45. 659

main(), .
, Qt
QTEST_MAIN().
,
.

45.1. . testxpp

#include <QtTest>
#include "MyClass.h"

// ==================================================
class Test_MyClass : public QObject {
Q_OBJECT
private slots:
void min();
void max();
};

//
void Test_MyClass::min()
{
MyClass myClass;
QCOMPARE(myClass.min(25, 0), 0);
QCOMPARE(myClass.min(-12, -5), -12);
QCOMPARE(myClass.min(2007, 2007), 2007);
QCOMPARE(myClass.min(-12, 5), -12);
}

//
void Test_MyClass::max()
{
MyClass myClass;
QCOMPARE(myClass.max(25, 0), 25);
QCOMPARE(myClass.max(-12, -5), -5);
QCOMPARE(myClass.max(2007, 2007), 2007);
QCOMPARE(myClass.max(-12, 5), 5);
}

QTEST_MAIN(Test_MyClass)
#include "test.moc"

.
MyClass ( 45.2).

45.2. MyClass.cpp

#pragma once

// ============
class MyClass {
660 VI. Qt

public:
int min(int nl, int n2)
{
return nl < n2 ? nl : n2;
}

int max ( int nl, int n2)


{
return nl > n2 ? nl : n2;
}
};

pro- ( 45.3) QT testlib.


,
.

45.3. TestLib.pro

SOURCES = test.cpp
HEADERS = MyClass.h
QT += testlib
TARGET = ../TestLib

,
, . ,
, . min( )
max () MyClass .
. :
********* Start testing of Test_MyClass *********
Config: Using QTest library 5.2, Qt 5.2
PASS : Test_MyClass::initTestCase ()
FAIL! : Test_MyClass::min ( ) Compared values are not the same
Actual (myClass.min(25, 0)): 25
Expected (0): 0
test.cpp(25) : failure location
FAIL! : Test_MyClass::max ( ) Compared values are not the same
Actual (myClass.max(25, 0)): 0
Expected (25): 25
test.cpp(35) : failure location
PASS : Test_MyClass::cleanupTestCase()
Totals: 2 passed, 2 failed, 0 skipped
********* Finished testing of Test_MyClass *********

initTestCase ( ) cleanupTest ( )
. -.
. ,
, : FAIL!, Test_MyClass::min()
Test MyClass::max(), (Actual) (Expected). !
, , -
45. 661

.
MyClass , 45.2. .
:
********* Start testing of Test_MyClass *********
Config: Using QTest library 5.2, Qt 5.2
PASS : Test_MyClass::initTestCase ()
PASS : Test_MyClass::min()
PASS : Test_MyClass::max()
PASS : Test_MyClass::cleanupTestCase()
Totals: 4 passed, 0 failed, 0 skipped
********* Finished testing of Test_MyClass *********

, .


QCOMPARE ( ).
.
QtTest
. ,
. ,
. , , data.
, 45.4, :
max_data { ), .
min_data ( )

45.4. testxpp. Test_MyClass

class Test_MyClass : public QObject {


Q_OBJECT
private slots:
void min_data ( );
void max_data ( ) ;

void min ( );
void max ( );
};

45.5 min_data(),
. QTest::addColumn ( ) .
, QTest::newRow ( ) . ,
, .
, :
min( ).

45.5. testxpp. min_data()

void Test_MyClass::min_data ( )
{
QTest::addColumn<int> ("argl" );
662 VI. Qt

QTest::addColumn<int> ("arg2" );
QTest::addColumn<int> ("result");

QTest::newRow("min_testl") 25 0 0;
QTest::newRow("min_test2") -12 -5 -12;
QTest::newRow("min_test,,) 2007 2007 2007;
QTest::newRow("min_test4n) -12 5 -12;
}

max_data() ( 45.6) mindataO


(. 45.5).
.

45.6. testxpp. max_data()

void Test_MyClass::max_data ( )
{
QTest::addColumn<int> ("argl" );
QTest::addColumn<int> ("arg2" );
QTest::addColumn<int> ("result");

QTest::newRow("max_testln ) 25 0 25;
QTest::newRow("max_test2") -12 -5 -5;
QTest::newRow("max_test3") 2007 2007 2007;
QTest::newRow("max_test4") -12 5 5;
}

, min ( ) ,

45.7,
. QFETCH ( ) argl, arg2,
result . ,
, ,
.
QCOMPARE ( ) .
.

45.7. testxpp. min ()

void Test_MyClass::min()
{
MyClass myClass;
QFETCH (int, argl);
QFETCH (int, arg2);
QFETCH ( int, result );

QCOMPARE(myClass.min(argl, arg2), result);


}

max 45.8
min ( ) , , MyClass::max()
MyClass::min( ).
45. 663

45.8. testxpp. max ()

void Test_MyClass: : ()
{
MyClass myClass;
QFETCH (int, argl) ;
QFETCH (int, arg2) ;
QFETCH (int, result);

QCOMPARE (myClass .max (argl, arg2), result);


}

main ( ) QTEST MAIN ( )


, :
QTEST_MAIN (Test_MyClass)
#include "test.moc"



QtTest .
,
QLineEdit. , .
edit() QLineEdit ( 45.9).
ABCDEFGH, QTest : : keyClicks ( ) ,
.
,
.
keyClickO, keypress () keyRelease ( ) ,
,
Qt : : Key.
(Shift, Ctrl Alt)
.
QCOMPAREO ,
.
, isModifiedO true.
QVERIFYO, , ,
, .
.

45.9. testxpp

# include <QtTest>
# include <QtWidgets>

/ , ========================

class Test_QLineEdit : public QObject {


Q OBJECT
664 VI. Qt

private slots:
void edit();
};

//
void Test_QLineEdit::edit()
{
QLineEdit txt;
QTest::keyClicks(&txt, "ABCDEFGH");

QCOMPARE(txt.text(), QString("ABCDEFGH"));
QVERIFY(txt.isModified());

QTEST_MAIN (Test_QLineEdit )
#include "test.moc"

QTest ,
, . :
moused ick ( ) ;
mouseDClick ( ) ;

mousePress ( ) ;
mouseRelease ( ) .
,
. ,
, .
mouseMove ( ) , .
mousedick ( ) :

QPushButton cmd:
QTest: :mouseClick (&cmd, Qt: :LeftButton) ;

QTestEventList
simulate ( ) . , :
, :

QTestEventList 1st;
1st . addKeyClicks ( "ABODE" ) ;
1st .addDelay (1000) ;
1st .addKeyClick (Qt : :Key_Backspace) ;
QLineEdit txt;
.
1st simulate ( &txt ) ;


QtTest .
. ,
, -
45. 665

MyTest: :max() (. 45.2),


:
TestLib max
. 45.1 ,
.

45.1.

- filename file

-silent

vl

-v2 -vl , QCOMPARE ( )


QVERIFY

-vs

-xml XML

-event delay ms (
).

, .
, .
.
, .
QObject.
QTEST_MAIN ( ) , main ( ) .
QCOMPARE ( ) .
, ,

.
QVERIFY ( ) . true,
. ,
.
, , QtTest
. , ,
private .
, , data.
. QFETCHO
.
QtTest .
46

WebKit

,
... ,
,
.

.

. , , ,
.
Web-,
, Web.
, Web, Web-
. ,
HTML- Web-
. Web-
.
, ,
Web-, ,
,
. , ,
iTunes (. 46.1) Apple. iPad, iPod iPhone
, Mac OS X, Windows.
www.apple.com/itunes/download/.
iTunes Web-,
iTunes, , .
.
. , , ,
, , , , , .
, iTunes Web- WebKit,
.
. , ,
Web- , , ,
, Web, ,
, Web-, Google,
Yahoo .
WebKit?
46. WebKit 667

. 46.1. iTunes


WebKit ,
Web-. Web- Konqueror,
KDE.
Apple , 2002 Web-
Safari, iTunes, Dashboard, Mail Mac OS X.
iPhone , , .
WebKit
, , HTML, XHTML, SVG, CSS, XML, ,
, JavaScript . . WebKit
, MIME- . WebKit
,
, MIME-. ,
WebKit . ,
Google Android WebKit
JavaScript.
668 VI. Qt

?
, Web-,
, ,
, Web-.
-,
Web- Web-.
,
. , ,
, . .
, .
, MIME-, , ,
.

, ,
.
WebKit Qt .

.


WebKit ,
Web-, Web-
. .
WebKit . WebKit
Qt 5 : QtwebKit QtwebKitwidgets. ,
, . ,
, Qt Quick (. VIII),
. WebKit
Web-. , WebKit
, Web-.
,

MIME-.
, WebKit
.
, ,
, Qt, Web-
.
WebKit ,
, Web-
.
,
, .
Web- :
46. WebKit 669

1. QWebView.
2. .
3. .
! ( 46.1),
(. 46.2).

****1 by
13 !


Google

!
1 , ,
, (1
256- (255- ).
e-mail *
256 (2) ,
, .
[ ] .
13 .

20


1200
1200
. .


,
.
gee* ...
...
:
11.09.2014
.
Altium Designer:


0 .
.
,
,

,

l
Altium Designer

_ . .

. 46.2. Web-

QWebView WebKit,
.
, .
. 46.1
Web- (webview) load(),
. ,
QUrl. show() .

46.1. Web-

#include <QtWidgets>
#include <QtWebKitWidgets>
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QWebView webview;
670 VI. Qt

webview.load(QUrl("http://www.bhv.ru ));
webview.show();

return app.exec();
}


,
- QT += widgets webkit webkitwidgets.

, Web- .
,
. , ,
. ,
-. ,
.
. ,
.

Web-
, , Web-
, :
Web-;
;
.
.


- ,
, . Web-
, .
, ,
, WebKit , ,
load(). . ,
, , ,
. www.bhv.ru ,
http://www.bhv.ru.
.


WebKit
. ,
, , -
46. WebKit 671


. WebKit QWebHistory.
QWebview history .
QWebHistoryitem.
.
, . ,
, ,
.
clear
QWebHistory.

, Web-
. ,
Web- , ,
. Web-
,
. QWebHistory
back forwardf), , QWebview
,
.


, ,
( ), , ,
, CSS, Web-, .
Web- ,
.
. ,
, WebKit
. ,
.
. QWebview
loadFinished ( ) , .
, . ,
, .
,
, loadProgress QWebview.
0 100, .

Web-,

, Web- ( 46.2-46.6),
. 46.3.
( 46.2) Web-
(webBrowser).
672 VI. Qt

. 46.3. Web-

46.2. main.cpp

#include <QtWidgets>
#include "WebBrowser.h"

int main(int argc, char** argv)


{
QApplication app(argc, argv);
WebBrowser WebBrowser;

WebBrowser.show();

return app.exec();
}

( 46.3)
: ( m ptxt),
Web- ( m pwv)
( m pcmdForward m pcmdBack). : slotGoO
slotFinished ( ) . , ,
, .
46. WebKit 673

46.3. WebBrowser. h

ipragma once

#include <QWidget>

class QLineEdit;
class QWebView;
class QPushButton;

/f ==========m=========

class WebBrowser : public QWidget{


Q_OBJECT
private:
QLineEdit* m_ptxt;
QWebView* m_pwv;
QPushButton* m_pcmdBack;
QPushButton* m_pcmdForward;

public:
WebBrowser(QWidget* wgt = 0);

private slots:
void slotGo ( );
void slotFinished(bool);
};

( 46.4) Web-
. ( m ptxt)
. Web- ( m pwv)
( m_pcmdForward) ( m pcmdBack).
Web- ,
.
setEnabled ( ) , Web- back()
forward().

( pprb). setvalue() Web-
loadProgress().
, ,
Go, stop Refresh. Go ( Go) .
slotGo ( ) ,
<Enter> . Stop
Web-,
Web- stop(). Refresh ( Refresh) Web-
, Web-,
.
slotGo().
674 VI. Qt

46.4. WebBrowser.cpp.

WebBrowser::WebBrowser(QWidget* wgt/*=0*/) : QWidget(wgt)


{
m_ptxt = new QLineEdit("http://www.bhv.ru");
m_pwv = new QWebView;
m_pcmdBack = new QPushButton("<");
m_pcmdForward = new QPushButton(">");

m_pcmdBack->setEnabled(false);
m_pcmdForward->setEnabled(false);

QProgressBar* pprb = new QProgressBar;


QPushButton* pcmdGo = new QPushButton("&Go");
QPushButton* pcmdStop = new QPushButton("&Stop");
QPushButton* pcmdRefresh = new QPushButton("Refresh");

connect(pcmdGo, SIGNAL(clicked()), SLOT(slotGo()));


connect(m_ptxt, SIGNAL(returnPressed()), SLOT(slotGo()));
connect(m_pcmdBack, SIGNAL(clicked()), m_pwv, SLOT(back()));
connect(m_pcmdForward, SIGNAL(clicked()), m_pwv, SLOT(forward()));
connect(pcmdRefresh, SIGNAL(clicked()), m_pwv, SLOT(reload()));
connect(pcmdStop, SIGNAL(clicked()), m_pwv, SLOT(stop()));
connect(m_pwv, SIGNAL(loadProgress(int)), pprb, SLOT(setValue(int)));
connect(m_pwv, SIGNAL(loadFinished(bool)), SLOT(slotFinished(bool)));

//Layout setup
QHBoxLayout* phbx = new QHBoxLayout;
phbx->addwidget(m_pcmdBack);
phbx->addwidget(m_pcmdForward);
phbx->addWidget(pcmdStop);
phbx->addWidget(pcmdRefresh);
phbx->addWidget(m_ptxt);
phbx->addWidget(pcmdGo);

QVBoxLayout* playout = new QVBoxLayout;


playout->addLayout(phbx);
playout->addWidget(m_pwv);
playout->addWidget(pprb);
setLayout(playout);

slotGo();
}

slotGo() ( 46.5). ,
load(), .
, , ,
. ftp://, http://
gopher://, , , -
46. WebKit 675

http:// .
, load().

46.5. WebBrowser.cpp. slotGoO

void WebBrowser::slotGo()
{
if (!m_ptxt->text().startsWith("ftp://")
&& !m_ptxt->text().startsWith("http://")
&& !m_ptxt->text().startsWith("gopher://")
) {
m_ptxt->setText("http://" + m_ptxt->text());
}
m_pwv->load(QUrl(m_ptxt->text()));

46.6 slotFinished ( ) ,
. ,
. .
, setHtml ( )
Web- .
, ,
, . ,
.
, . ,
,
( m ptxt),
. uri ( )
Web- ( m pwv).
.
, , QWebHistory
: canGoBack ( ) canGoForward ( ) .
.

46.6. WebBrowser.cpp. slotFinished ()

void WebBrowser::slotFinished(bool bOk)


{
if (!bOk) {
m_pwv->setHtml("<CENTER>An error has occurred "
"while loading the web page</CENTER>"
);

m_ptxt->setText(m_pwv->url().toStringO );

m_pcmdBack->setEnabled(m_pwv->page()->history()->canGoBack());
m_pcmdForward->setEnabled(m_pwv->page()->history()->canGoForward());
676 VI. Qt

Web-.
WebKit ,
Web-,
. Qt
WebKit QWebview,
.
47


Qt Creator

,
,
.

(IDE, Integrated Development Environment)


, .
. Qt, Qt Creator
Qt. Qt Creator

, Qt- C++, QML (. VIII).

. IDE Qt Creator
(. 47.1).

Qt Creator



Qt
-

1


Qt Designer

. 47.1. Qt Creator

, Qt Creator

Qt Help, .
Qt ,
Qt Creator.
Qt Creator , ,
. Windows MinGW
(Minimalist GNU for Windows), Qt. Qt Creator -
678 VI. Qt

Visual C++ 2010, 2012 2013


. Mac OS X Qt Creator C++,
XCode.

, XCode C++,
. Preferences Downloads
Command Line Tools.


. ,
.
, , ,
. ,
, .
Qt Designer (. 44)
, .


Qt Creator
(. 47.2), . -

. 47.2. Qt Creator
47. Qt Creator 679

.
.
, .

Hello Qt Creator
1.
Qt Creator.
, ,
( pro-). ,
- Qt Creator,
, pro-
Qt Creator.
Qt Creator ,
. -, ,
.
Qt Creator .
(. 47.3) Qt
Widget, :
Qt Widgets ,
;

? QtCxitor
flpaaia * 0

Hu * Qt Widget) *1 Qt
Qt Quid . .
Qt.
Ot
Oesttcp Qt*
Qt Quid , .
: t sktop

| ... |

- Its 1 IjMg IOKcMcoffcct5tTiI|K:<cifbQMUJsl

. 47.3.
680 VI. Qt

Qt Quick ,
QML, C++;
Qt ;
Qt Quick Qt Quick.

Qt Widgets ....
, . 47.4,

, , Qt Creator .

* QtCrjt 0 1

*| 0*

! Qt VAdgets

! ie
Qt VAdgete. QAcpfeation

Deta*

*: MyAppJ

; C:\QtS,3,2\Toots\Qt/Mtor \ .,

* * (( 1|! ) I B.'-a Igj, **1 I ' QML/Xj I

. 47.4.

, .
, ,
... . .
Qt , ,
(. 47.5).
.
Qt.

,
Qt,
.
.
47. Qt Creator 681

? Qt Cator S
* Otrtaj j

Qt Widgets

t ot.irinet
location
Qt Creator

Delate

g (% Desktop Qt 5,3.0 MSVC 2010 OpenGL 32bit A

g C:VQt5.3.2\Tocte\Qt&ealDr\bn\buid-MyApp-OesUe<>_Qt_5_3_Q_M5VC2QtQ_OpeftGLJi2bt-Debug ..,

g C:lQt5.3.Z\Tte\QtCreator\bri\bijld-MyApp-OesWop_Qt_5_3_0_MSVC201Q_Qp<2._32bt-Retee 06p... J

(Ctil ) (tij5 '4 Koncoib coop* |>|* QM./JS I

. 47.5.

(. 47.6)
, (*.h), (*.)
(*.ui). ,
Qt Designer, 44,
, .
,
Qt Designer.
,

(. 47.7). , ,
Qt Creator .
, . 47.8.

. . 47.9
, , ,
.
(. . 47.8) :
. pro, mainwindow.h, main.cpp, mainwindow.cpp mainwindow.ui.
,
, . 47.10,
... , ,
.... ...,
682 VI. Qt


* 0


* 1

rfc*wee Qt Vrtdgeti

I1
Location
6&-, **) , * .
Os

:
: QManVMhdow .
: marmrckm.h

; 1.
: [VJ
: irwwndow.u

I - | >< |1< |1 |
. 47.6.

? QtCleatoi


'

rfcnno**e QC WBjjets

:

: < > *

*!( *

:\QeS.3,2\T*el\QeCr*eor\bn\KyApp.
U1D.
Balnolndov.
kauivlndov _
kainuiiidev. til
HyApp.pre

| ]

I * P- ij |jiPejy rc-Ti>T,,i >- s Ipij nemo * I *: lj CKO'\ vM:'?I

. 47.7.
47. Qt Creator 683

v * 0+ <
.
h

1, ...
mainwindow.h

< main.cpp

I" j mainwindow.cpp

........
-
[! I ... III

+
ES
a inWin dew
MamWmdow (QWidget * = 0}
& -MainWindow 0
Vi ui Ui::MamWmdow *
main (int. char *[])

'\?* + X

.

h
[_,mainwindow.h
*
|"1 main.cpp
mamwmclowcpp

mainwindow.ui

. 47.8. . 47.9.

. 47.10.
684 VI. Qt

(. . 47.3), .
.
.
..., .

Qt Creator

Qt Creator.

mainwindow. Qt Creator

*{/1 * X mainwindow. *> * : 1, : 1 + X
include "meinwindow.fa"
pro include "ui_mainwlndow.h"
*
> mainwindow h MainWindcw::MainWindow(QWidget "parent)
QMainWmdow(parent),
* .
- main ul (new 01::MamWindow)
- mainwindow (
I
ui->setupUi (this) ;
* )
| mainwindoM.nl
MarnWindow::-MamWindov()
* {
delete ul;
)

12:31:23: ...
12:31:23: , qmaJce
12:31:23: : C:\Prcgram Files\Microscft Visual Studio iO.OWC
\BIH\nmake .
"C:\Program FilesNMicroscft Visual Studio 10.0\VC\BIN
\nmake.exe" -f Makefile. Debug
12:31:23: C:\Pragram Flles\Mlcrosoft Visual Studio !0.0\VC\BIN
\nmake.exe
12:31:23: : 00:00.

- (Ctrl* )

. 47.11. Qt Creator

Qt Creator
(. 47.11):
;

;
(, , . .)
;
;

( ,
).
.
47. Qt Creator 685


( )
. ,
, ,
. ,
.
,
Qt Creator. ,
.


, . 47.8. ,
,
.
.


,
.
. , .
(. 47.12).

. 47.12.


,
. Debug
,
Qt , : .
686 VI. Qt

Android, iOS
. ., , . 47.12,
.
,
.
.
.

. 47.13.

,
(. 47.13). , .
, . ,
Qt Creator,
.
.
(*.h, *.) .
Qt Designer
(*.ui).
drag & drop, .
widget. ui,
Qt Designer (. 47.14).
. ,
(Filter) Label.
, ,
. .
Display Widgets Label .
TextLabel. ,
, .

,
. : Hello Qt Creator
(. 47.15).

(. 47.16).
47. Qt Creator 687

. 47.14. Qt Designer

. 47.15.

*"*1 MainWinclow CD a *

Hello Qt Creator

. 47.16. Hello Qt Creator


688 VI. Qt



, ,
. , , .

?
Qt Creator
,
. , , ,
, , ,
.
. , ,
: /*, -
, , : *) : */, ,
. ,
, fir for, ,
. ,
.
Qt Creator :
;
;
;
;
-;
;
-;
.
, ,
| | .



. Qt Creator
. : ,
, ,
. ,
.
(. 47.17), ,
.
47. Qt Creator 689

Widget: :Widget(QWidget *parervt)


: QWidget (parent) , ui(new Ui: :WidgetClass)
{
ui->setupUi(this) ;
>
|flidget: :-Widget() [ .
{. .} ]

. 47.17.


/ ,
Qt Creator
.
, <11>+<>.
, ,
, ,
. . 47.18.

-
J
connect(qApp, SIGNAL(
f

} aboutToQuitO
'
cornrnitDataRequest(Q5essionManager&)
destroyedO
d s troy d (QObj cl*)
focusChanged (QWidget*,QWidget*)
lastWindowClosedO
saveStateRequest(QSessionManager&)
unixSignal(int)

. 47.18.



, Qt, ,
INCLUDEPATH (*.).



.
,
Qt Creator.
/ (. 47.19).
(. 47.20),
. ,
()
( ). , ,
. -
690 VI. Qt


Ctrl +Z 3X44 widget, S Widget:

Ctrl+Y #include "widget.h"


"ui_widget.h"
Ctrl+X
Ctrl + Widget::Widget(QWidget *'paren
QWidget(parent),
Ctrl+V
! d ui(new Ui::Widget)
{
Ctrl + A
ui->setupUi(th3);
}
I

/ I / Ctri+F
... Ctrl + L
6 .. ,

F3
>1 , Shrft+F3

Ctrl + =

. 47.19. | /

. 47.20.

, .
, , .
- , .
| / | (. . 47.20):
;
;
;
.
47. Qt Creator 691

, , . 47.21.
.
(. 4),
. ,
,
. h,
.

. 47.21.


(. 47.22).
, ,
,
. :
( *).

. 47.22.

, , Qt
Locator ().
, ,
692 VI. Qt

<Ctrl>+<K>. ,
:
1 ;
: ;
;
? ;
f , ;
, ;
.
. 47.23 .



7


> f
lain 1
riclcj m
rtdg
ridg
cent

widget,
main.cpp

C:\LJ sers\ali n a\Downloads\u ntitle
jOwj C:\Users\alina\Downloads\untrtle
|In | widget.h C:\U sers\a 1 i n a\Downl ad s\u ntitle
widgetui C:\Users\alina\Downloads\imtitle
1 i]| 1HI [j
. 47.23.

, ,
. ,
,
<Ctrl>+<Shift>+<U>.
,
(. 47.24).
, , /
. ,
. Qt Creator .
, ,
. |
<Ctrl>+<Shift>+<R> (. 47.25)
, .
, .
.
47. Qt Creator 693

5 Colors: :parseArgs (arcc, argv) ;


60
61 1 F2
62
/ Shrft+F2
63
64 of (Color Ctrl + Shift + U
65 mainW Ctrl + Shift +
66 else {
67 mainW
6S rr.alnW
69 > Ctrl +1
/ Ctrl +/
artrsticS

73
74 V| Ctrl +V

< rrr
-
C :\QtSD D e m s 4,7 qt d e m main,cpp ( 1)
C:\QtSDK' Pemos.4. 7 .qtdemo mainwindow.cpp (25)
* C:\ OtSD K' Dem s\ 4, 7 . qt d cm o\m a i nwi n d ow, h ( 3)
51 class MainlilindoTiT : public QG-raphicsView
HainWindow (QUidget = 0);
~ i i n do w ( ) ;
* C:\ OtSD K\ D em s\ 4 , 7 qt d e m o', m enuma n a g er. c pp (1)
409 void HenuManager : : init (MainWindow
* C:\ OtSD D e m s 4 . 7 qt d e m m e num a n a g e r. h (2)
'

void init (MainWindow ''window);


i n TiT i nd w * w i ndo w;

. 47.24.

jerr.c_ter. : sraphicsiteir.
6S i
69
70 publicy
71 Deir-olter- 0) ;
72 virtual i i ypcopor i F2
73 Shift+F2
74
Ctrl+Shift+U
75
76 On Ctrl+Sluft+T
77
"7 J Ctrl + Shift+R

Ctrl +1
Jai . 1 1 Ctrl +

01 3ceceFer.c
S4
85 qreai QJ Ai Ctrl +V
bo cl IccKed;
DsmoIterr.An-iir.aTQn *curren~Anir,ariori;

m
Demoltem

, I X
l> 1ZJC QtSD D m 5 4 7 qtdemodemoitem.cpp (27)
,

I' QtSDK Demos 4.7 qtdemo demoitem.h ()


-* QtSD Demos' 4.7 qtdemo demoitemanimation.cpp (5)
46
m 179
m
131 return (Demo Item *) this-> item ( ) ;

196 Demoltem *demoItem = (Demoltem *) item ( ) ;
m
196 Demoltem *demo Item (Demoltem *) item ( ) ; =
1 .\ QtSD D
C:\OtSDK, Demos .4.7 qtdemo demotextitem.epp (3)
[7] C:\QtSDK\Demos\.4.Aqtdemo\demotextitem.h (1)

'

'' OtT'b Demos'. 4.7 .qtdemo .clod- item.cpp (l)

. 47.25.
694 VI. Qt


,
,
. .


, <Shift>,
, , .
<Shift> <Alt> ,
(. 47.26).
"Begin";
it i = 0; i < 10; ++i
ebugQ "i:" i;

. 47.26. <Alt>


(
. 47.27),
<Ctrl>+<l>, , .

qDebugQ "Begin; qDebugQ "Begin";


for (int i = 0; i < 10; for (int i = 0; i < 10; +ti) {
qbebuaO qDebuqO i;" i;

qDebugQ "End"; qDebugQ "End";

. 47.27. <Ctrl>+<l>


,
.
<Ctrl>+</>
, . 47.28.

//
qDebugQ "Begin"; // qDebugO "Begin;
for (int i = 0; i < 10; ++i) { // for (int i = 0; i < 10; --i) {
qDebuqQ "i;" i; 14 // qDebugQ i:"' i;
// >
qDebugQ "End"; // qDebugQ "End";
//

. 47.28. <Ctrl>+</>
47. Qt Creator 695


, (*.h) - ,
.
. : ,
<F2>,
(. 47.29). ,
.

15 public:
.h epp
10 Widget :: -Widget ()
Widget (QWidcret *i>arent = 0);
|~Widget () ; 11
delete ui;
13 }

. 47.29. <F2>

,
.
, , .
Qt Creator
<F2>,
.

<Ctrl> ( Windows Linux) <Command> ( Mac OS X)
, , ,
Web-.
, <F2>. ,
.

,

.
,
<F1> ,
. 47.30.

main.cpp f main(int, char *0) w ++ X Go to Help Mode


<QtGui/QApplication> Home All Namesoaces

"widget. h
All Classes Main Classes

int mainCint orge, char *argvD)


|\Jt4 Grouped Classes

{
Modules Functions
QAppllcation aCargc, argv};
Widget w;
w.showQ;
QApplication Class Reference
return a.execQ; [OtGui module]
>
The QApplication class manages the GUI application's control flow and
main settinas. More...
<QApplication>

. 47.30. <F1>
696 VI. Qt


, - ,
Qt Creator , .
<Alt>+<V>, <Alt>+<l>.



3
GDB. Qt Creator GDB .

. ,

, .
.
Qt Creator
<F5> , Qt Creator
(. 47.31).

. 47.31.

, ,
. , ,
.
47. Qt Creator 697

. ,
.
, ,
++.
, .
:
;
;
;
.


. ,
, ,
. , int float
, .
, . ,
,
, .


,
C++.
, ,
. .
, . ,

(. 47.32). , -
. ,
, .
, .
, , , .
,

w. show ( ) ;
_2 #endif

14|

. 47.32.
698 VI. Qt

.
,
.

. , . 47.33, , return
, .
-
, .
,
:
, ;
, , ,
;
,
. - ;
, ,
- .
, .


.
,
. . , .
, , ,
. ,
(,
Mac OS X Linux ).
. 47.33
,
. , ,
,
,
test ( ) .

void test();

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


{
QApplication a(argcf argv);

rest();

iQi coltect2: Id returned 1 e>at status

. 47.33.
47. Qt Creator 699

, ,
.


( )
, .
,
, .
, , ,
, , . .
, , .


,
,
. : , ,
, . ,
, .
,
, . ,

,
,
. , 45,
.

.

. ,
qDebug().
,
.
.
. qDebug ( ) 3,
.

main ( ) <F9>.
(. 47.34). ,
. <F5>
Qt Creator,
main ( ) .
, . Flo
, ,
.
.
700 VI. Qt

. 47.34 ,
. , .
,
QApplication. , ,
, , ,
.
, . 47.35.
.
,
.

0 E irvt matoCtnt urge, char *argvO)


{
> 6 QApplicatiQn a Orgc, orgv};
MninWincfaw w;
w.strowO;
return a.execQ;
}

. 47.34. . 47.35.

:
Step Over ();
Step Into ();
Step Out ().
(. . 47.36)
: Continue
Stop Debugger. Stop Debugger
, .
Continue
Stop Debugger .
.

Step Over

. ,
, , , .
, , ,
(. 47.36).

tot min(int orgc, char *argvED


{
QAppUcatton a(argc, argv);
MainWindow w;
w.showO;
return o.execO;
10 }

. 47.36. Step Over


47. Qt Creator 701

Step Into
, ,

.
. ,
Mainwindow (. 47.37). ,

Step Over, .

. MainWindow i :MainWi.ndowCQWidget parent)


: QMainWinttoivCparent), ui(neiv Ui: iMainWindowClnss)
{
ui->5etupUi(this) ;
}

. 47.37. Step Into

Step Out
,
, , . ,
, show(),
(. 47.38).

9 irvt reii.n(i.nt argc, char argvCD


{
QAppli.cati.on afargc, argv);
MainWindow w;
-V> [v.showO;
return a.execQ;
>
. 47.38. Step Out


,
. , ,
Step Into Step Over,
. ,
, ,
, .
, .
, Qt Creator
. ,

. , ,
.
, ,
| .
702 VI. Qt

, ,
. ,
, , (. 47.39).

.

: Thread 2... : end-stepping-range


A/ipee
S qMain(int, char **) C :\QtSD K\D em s . 4, 7 qtde m m a in c pp , 72 0x40 14c a
V 9 C : . QtSD K\D e m s\4. 7 . qtd e m m a i n wi n dow,
, , .. 61
9,1 a i nWin d w:: a inWind w( QW i dg et 0x4016
9 , 2 M a i nWin dow:: M a i n Wi nd ow(QWidg et 0x401861
10 - C :\QtSD K\D e m s\4.7\<|td e m \sca n item . c pp 51
10. 1 ScanItemc;ScanItemi(QGraphicsScene 0x40 a 16 a
10,2 Sea nllem ::Sc a nttem ( QGra ph ics Sc ene 0x40 a If c
II - C;\ QtSD K'D e m s 4.T qtd e m \ dock item c pp
, 49
11, 1 Doc Utem::Doddtem(Doc kitem ; :0 RIE NTATIO N . 0x409877
11, 2 Dockltem : ; D c kit em (D c Utem :: 0 RIE NTATIO N. 0x40996d
rrr

. 47.39.

(Local and Watches)



.
, , , ,
(. 47.40). .
, .
, ,
. ,

main.cpp ** main(intj char *[]) ~ X Tun


{ app > QApplication
49 QTime time; arge 1 int
50 time.restart ( ) ; > argv <1 > char*"*
51 while (time.elapsed ( ) < ) * matnWindow MainWindow
5? QGraphicsView QGraphicsView
background unavailable synchronous data QPLxmap


companyLogo @0x22fe78 Imagehem
. * Demoltem Demoltem
>5 int main(int arge, char *argv[])
QGraphicsItem QGraphicsItem
56 { : currGuide @0xle75e28l Guide
57 Q 11 RESOURCE(qt demo) ; currentAnimation @0xa DemoftemAnimatiorr
52 QApp location appfarge, argv) ; guideFrame 1 57l43258e+033 float
59 Colors::parseArgs large, argv) ; guidedPos (15(56486763 l681092e- 304. 5.2832263027.... QPointF
(MainWindow. malnWindow; hashKey ; ;- QString
61 MenuManager :: Instance ( ) ->nit ( SmainWinc locked 56 boot
62 malnWindow.setFocus ( ) ; neverVisible 16 boot
63 noSubPixeling 176 bool
64 if (Colors::fullscreen) = opacity l564254735953794le-304 qreal
malnWindow.showFuliScreen ( ); prepared false boot
sharedimage 0x0 Sharedlmage
startFrame 3.2l376592e-039 float
62 malnWindow.show ( ) ;
adjustSire 6 bool
image Qlrnage
maxHeight 14624262 int

_ artisticSleep (500);
_ thit
__ _
maxWidth
.r-Ao
0
_a
< curh vain*:- _
int

. 47.40. ()
47. Qt Creator 703

.
, .
.
, , ,
, ,
,
, .
Qt Creator Qt-,
Qt- ,
. , ,
, . ,
QFile, .
QList, .

(Call Stack)
,
, . ,
main Mainwindow,
setupui () . ., , . 47.41.

L Widget, giw;
( ! QGLForir,a.t : :hasOpenGL ( )
|| l giw. format ( ) .
directRendering ( )
|| ! (QGLFonaat ::openGLVersionFlags ( ) & QGLFor
.
|| giw depth ( ) <24
)
else
if (Colors: :verbose)
qDebug (} OpenGL not supported by cur re


0 Colors::detectSystemResources colors, cpp 3L4 0x41cdd9
1 Colors parseArgs colors, cpp 199 0x41b9ea
2 qMain main, cpp 59 0x401456
3 WinMain |tmain_win.cpp 13i 0x4ifa22
4 main 0 0x411748

. 47.41.

Qt Creator ,
Qt.
.
.
, Qt Creator:

;
704 VI. Qt

;
;
,
Qt Designer;
;
.
Qt Creator .
, , .
.
,
Step Over, Step Into, Step Out
.
48


Qt 4 Qt 5
, , , , , .

Qt , 4 5
. Qt 5
, - .
, Qt 5,
Qt 4 ( ), .
, , ,
,
Qt 5.

Qt 5 Qt 4
Qt 5,
.
. , , ,
, , , ,
.
QtGui
QtWidgets.
Qt 5 Qt3Support, Qt 4
Qt 3. , , ,
, .
Phonon Qt 5.
QtMultimedia (. 27).

.

Qt 5
, , . , ,
Qt ,
, Qt Assistant,
706 VI. Qt

. Porting Guide Porting C++


Application to Qt 5, Qt 4 QML-,
Porting QML Applications to Qt 5.
, Qt 5.

, , Qt 5 Qtwidgets,
,
, QtGui,
Qtwidgets. , :
tinclude <QtGui>
:
tinclude <QtWidgets>


,
, .

:
QT += widgets



, Qt 5 fixqt4headers.pl
qtbase//. ,
.

QWorkspace , QMdiArea.
. :
tinclude <QWorkspace>
:
#include <QMdiArea>


QString toAscii ( ) fromAscii ( ) . ,
, toLatinio fromLatinl() .
, :
QByteArray ba = str.toAscii ;
:
QByteArray ba = str.toLatinl ();
48. Qt 4 Qt 5 707

qvariantvalue ( ) Qt 5.
QVariant::value<T>( ) . , varPix:
QPixmap pix = qVariantValue<QPixmap>(varPix);

value<T>():
QPixmap pix = varPix.value<QPixmap>();

qFindChildren<T*>()
qFindChiidren<T>(),
, Qt 5 .
QObject::findChildren<T*>( ) . , :
QList<QWidget*> 1st = qFindChildren<QWidget*>(pwgt);
:
QList<QWidget*> 1st = pwgt->findChildren<QWidget*>();


QFtp QHttp Qt 5 .
QNetworkAccessManager (. 39).

WebKit
QtwebKit Qt 5 : QtwebKit QtwebKitwidgets,
:
#include <QWebKit>
:
tinclude <QWebKitWidgets>
:
QT += webkitwidgets



Q_ws_*. Q_os_* :
Windows: Q WS WIN Q OS WIN;
Mac OS X: Q WS MACX Q OS OSX;
Linux: Q WS XII Q OS LINUX.

Plug-ins
Qt 5 , Qt 4
Q_EXPORT_PLUGIN Q_EXPORT_PLUGIN2 Qt 5 .
Q_PLUGIN_METADATA.
708 VI. Qt

, Qt
, ,
JSON-, .
Q PLUGIN METADATA Q OBJECT,
IID JSON- :
Q_PLUGIN_METADATA(IID "com.neonway.Aurochs.Indlnterface" FILE "indicator.json")

QPrinter
, ,
QPrintSupport.
:
QT += printsupport

QAudioFormat : QAudioFormat::setFrequency()
QAudioFormat::setSampleRate (), a QAudioFormat::
setChannels() QAudioFormat::setChannelCount().
.



CONFIG, QT . , :
CONFIG += qtestlib
:
QT += testlib

Qt 5 Qt 4

!
,

, , , ,
Qt 5 , ,
Qt 5, Qt 4.
, Qt 5 ,
,
, PowerPC, , , Phonon,
BlackBerry 10 API -
. , , ,
.
, - Qt 5, Qt 4.
,
Qt 4 , -
48. Qt 4 Qt 5 709

. ,
Qt 4.
, , pri-,
, . 48.1
.
,
.

48.1. main.pri

greaterThan(QT_MAJOR_VERSION, 4) :
DEFINES += Q_QT5
}
else: macx {
DEFINES += Q OS OSX Q QT4

else {
DEFINES += Q_QT4
}

Mac OS X Q_os_x,
Qt 4 .
Q QT4 Q QT5 , Qt
. ,
:
#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
// Qt5-Kcm
#endif

:
#ifdef Q_QT5
// QtS-
#endif
, , ,
, pri- (. 48.1).
Qwidgets, Qt 5. , Qt 4,
Qwidgets . ,
-:
include(main.pri)
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
. , Qt4
QtGui, Qt 5 Qtwidgets. ,
:
#ifdef Q_QT5
#include <QtWidgets>
#else
#include <QtGui>
#endif
710 VI. Qt

, ,
, . ,
.
QtWidgetsBridge.h Q_QT5 WFlags
Qt4 ( 48.2).

.

48.2. QtWidgetsBridge.h

#ifdef Q_QT5
#include <QtWidgets>
namespace Qt {
typedef WindowFlags WFlags;
}
#else
# include <QtGui>
#endif

Qt 5 QDesktopServices, QStandardPaths.
,
, QDesktopServices QStandardPath.
MStandardPaths. 48.3 .

48.3. MStandard Paths.h


QDesktqpServioes QStandardPath

#ifdef Q_QT5
#include<QStandardPaths>
#else
# i nc1ude <QDes kt opse rvi ce s >
#include<QStringList>
#endif

class MStandardPaths {
public:
enum MStandardLocation {
DesktopLocation = 0,
Document sLocat ion ,
FontsLocation,
Appl icationsLocat ion ,
MusicLocat i on ,
Movie sLocat ion,
PicturesLocation,
TempLocation,
HomeLocation,
DataLocation,
CacheLocation,
48. Qt 4 Qt 5 711

// Qt5 specific locations


GenericCacheLocation,
GenericDataLocation,
RuntimeLocation,
ConfigLocation,
GenericConfigLocation

static QStringList standardLocation(MStandardLocation type)


{
#ifdef Q_QT5
return
QStandardPaths::standardLocations((QStandardPaths::StandardLocation)type);
#else
return QStringList()

QDesktopServices::storageLocation((QDesktopServices::StandardLocation)type);
#endif

MStandardPaths MStandardLocation, Qt 4
Qt 5. MStandardPaths::standardLocation () ,
Qt QStandardPaths::standardLocations ()
Qt 5, QDesktopServices::storageLocation ( ) Qt 4.

Qt 4 Qt 5
. - Qt 4 Qt 5 .
, Qt 5 , Qt 4,
.
, Qt 5, Qt4,
.
VII

Qt Script

49.
50.
51. Qt Script
52. Qt Script
49

,
- - .
C++
,
.
, . ,
.

(workaround), ,
- ,
.
,
, .
,
, , ,
.
,
,
C++, .
, ,
. ,
, C++.

.
,
, Microsoft Office, CorelDRAW,
Macromedia Flash, Emacs, Audacity, TraderStar . .
QtScript , ,
, C++ Qt.
C++, , ,
Qt-, Qt Script,
-262 ( , JavaScript 2.0, JScript.NET Flash
ActionScript).
716 VII. Qt Script

Qt Script - ,
Qt. ,
. C++
Java, . ,
. ,
, JavaScript
.
, Qt,
Qt- , ,

.


,
, (properties),
, Qt.
, , (Meta Object
Compiler). , , QObject,
Qt Script, , ,
, Q OBJECT
Q PROPERTY, 2.
Qobject, ,
.
Q INVOKABLE :
Q_INVOKABLE void scriptAccessableMethod ();
, Qobject
.
Qt .
, QObj ect, Qt Script,
( 49.1).

49.1. , Qt Script

class MyClass : public QObject {


Q_OBJECT
Q_PROPERTY(bool readonly WRITE setReadOnly READ isReadOnly)

private:
bool m_bReadOnly;

public:
MyClass(QObject* pobj = 0) : QObject (pobj )
, m_bReadOnly ( false )
{
}

public slots:
void setReadOnly(bool bReadOnly)
49. 717

{
m_bReadOnly = bReadOnly;
emit readOnlyStateChanged();
}

bool isReadOnly() const


t
return m_bReadOnly;
}

signals:
void readOnlyStateChanged();
};

49. 1 , QObject,
(mjoReadOnly).
false. (setReadOnly ( ) )
(isReadOnly ( ) ) m bReadOnly. :
? -
, .
, , ,
readonly, .
setReadOnly( ) isReadOnly ,
.

:
myObject.setReadOnly(true);
print("myObject is read only:" + myObject.isReadOnly());

C++,
. ,
:
myObject.readonly = true;
print("myObject is read only:" + myObject.readonly);

QObject,
. QtScript
,
QObject, .
QtScript,
. .
,
,
Qt .
. 49.1 ,
, :
3 4. ,
Qt Script. ,
718 VII. Qt Script

*
Qt
| 1 ({
QtScript
2 (]4 >

. 49.1.

,
.
QObject , , ,
, QObject? ,
, Qt,
.
(wrapper),
QObject.
. ,
C++, Qt ( 49.2).

49.2. C++, Qt

class NonQtClass {
private:
bool m_bReadOnly;

public:
NonQtClass() : m_bReadOnly(false)
{
}

void setReadOnly(bool bReadOnly)


{
mJoReadOnly = bReadOnly;
}

bool isReadOnly() const


(
return m_bReadOnly;
}

49.2 NonQtClass .
,
, 49.3.
49. 719

49.3.

class MyWrapper : public QObject {


Q_OBJECT
Q_PROPERTY(bool readonly WRITE setReadOnly READ isReadOnly)

private:
NonQtClass m_nonQtObject;

public:
MyWrapper(QObject* pobj =0) : QObject(pobj)
(
}

public slots:
void setReadOnly(bool bReadOnly)
{
m_nonQtObject.setReadOnly(bReadOnly);
emit readOnlyStateChanged();
}

bool isReadOnly() const


{
return m_nonQtObject.isReadOnly();
}

signals:
void readOnlyStateChanged();
);

MyWrapper, 49.3,
NonQtClass setReadOnly () isReadOnly ()
. readonly,
. MyWrapper
, 49.1.


, , -
, , 2 * 2 4?
QtScript ( 49.4).
-:
QT += script

49.4. QtScript

#include <QtCore>
tinclude <QtScript>
720 VII. Qt Script

int main(int argc, char** argv)


{
QCoreApplication app(argc, argv);

QScriptEngine scriptEngine;
QScriptValue value = scriptEngine.evaluate("2 * 2");
qDebugO value.toInt32();
return 0;
)

49.4 scriptEngine.
evaluate( ) , .
.
: , , , QVariant . .

isT ( ) , .
, , , ,
49.4 :
if (value.isNumber()) {
qDebugO "Number";
}


, ,
.
:
if (value.isError()) {
qDebugO "Error:" value.toString();
)

,
Qt-
. ,
1 (. 1.1), Hello, World !
(. 49.2), 49.5.

. 49.2.


( ,
QtScript):
QT += script

QtScript:
# include <QtScript>
49. 721

49.5.

iinclude <QtWidgets>
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QLabel lbl("Hello, World !");
lbl.show();
return app.exec();
}

, 49.4,
.
.
, 49.6.

49.6. ,

#include <QtWidgets>
#include <QtScript>
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QLabel lbl;

QScriptEngine scriptEngine;
QScriptValue scriptLbl = scriptEngine.newQObject(&lbl);
scriptEngine.globalObject().setProperty("lbl", scriptLbl);
scriptEngine.evaluate("lbl.text = 'Hello, World !'");
scriptEngine.evaluate("lbl.show()");
return app.exec();
}

49.6 .
QScriptEngine, .
newQObjectO lbl,
QScriptValue.
. ,

QScriptValue::setProperty().
Qt Script,
evaluate (), .
(lbl), text "Hello, world !".
show().

,
.
722 VII. Qt Script


.
.
Qt QtScript
.
C++ . Qt Script
Script , .
Qt QObject
.
50

- , .
, ,
.
.

, .
, JavaScript ActionScript,
52,
.
,
C++ Java. , ,
, , , main ( ) C++,
, , .




,
. ,
. . 50.1
Qt Script.

50.1. Qt Script

break case catch const


continue default do else
finally for function if
in new prototype return
switch this typeof throw

try var while with

, ,
. 50.2.
724 VII. Qt Script

50.2. Qt Script

boolean byte char throws


double enum export float
goto implements import int
interface long native short

, . 50.1 50.2,
.

. ,
, ,
, , .
,
. Qt Script
(
), :
//
/*

*/

,
, ,
. Qt Script ,

. , , C++ Java. ,
.
var.
.
:
.
: ,
;
: !, ?, |, < . .;
(. . 50.1 50.2);

.
.
var.
50. 725

var ; //
var = 100; //
var i, j = 100; //
//
.
, undefined, undefined.
:
var ; // Undefined undefined
var
, ,
. :
str = "Hello";

, , ,
.

, (;).
, -
.


Qt Script ,
,
. Qt Script :
( ), .


32- .
-2147483648 2147483647. ,
.

, ,
, .
0 7.

. 0
9 F.
:
var xDec = 123; //
var xOct = 023; //
var = OxFF; //


32- .
-1.17549435-38 3.40282347+38.
726 VII. Qt Script

.
, .
, . :
var fExp = 23.4524-12; //
var f = -13.3451; //


UNICODE.
( ') (") . :
var strl = "Hello"; //
var str2 = 'Hello'; //
var str2 = 80's"; //

,
. 50.3. , ,
V :
var str2 = '80V s';

50.3.

\
\t
\
\v
\
\"

V
\\


( ) : true (
) false (). ,
:
var b = true;
b = (3 == 5); //b=false



typeof ( ) . , n, f, b, str
unknown, - , :
var = 7;
var f = 5.2018;
50. 727

var b = true
var str = "Hello";
var unknown;
print(typeof(n));
print(typeof(f));
print(typeof(b));
print(typeof(str));
print(typeof(unknown));
:
number
number
boolean
string
undefined


,
Qt Script, Qt-:
Qt\5.3\Src\qtscript\examples\script\qscript.

,
. ,
unknown, , typeof ( )
undefined. , .
, . :
var v = "Hello"; //
v = 32.3; //

, ,
. . ,
,
,
. ,
:
var = 56; //
var f = 0.27; //
var res = n * f; // : 15.12
.
parseFloatO parseinto,
.
, :
var f = 3.5;
var n = parselnt(f);
print(n);

f "3.5",
. ,
, , .
3.
728 VII. Qt Script

, , ?
var = 7, f = 5.2018, b = true;
var resl = n + " is a number";
var res2 = f + " is a float number";
var res3 = b + " is a boolean value";
print(resl);
print(res2);
print(res3);


:
7 is a number
5.2018 is a float number
true is a boolean value

, + , .

, .
const.
. :
const num = 2;
const strName = " ";

: infinity (
), NaN (Not a Number, ) undefined (
).

,
, .


.
, .
. :
= 13 13.


.
: () ().
:
, (+). : + ;
, (-). : - ;
50. 729

, (*). : * ;
, (/). : / ;
, (%). : % .
, ,
. . 50.4 .

50.4.

X += . = +
-= . = -
X *= . = *
X /= . = /
X %= . = %

:

(++) ( ).
, .
, ++i , i = i + l, i
, i = i - l.

. ,
. , :
var i = 0;
var = ++i;
i ,
. 1 .
.
var i = 0;
var = i++;
i ,
i .
0.



. ,
, .
. .
,
.
:
(&);
( | );
730 VII. Qt Script

();
;
;
>.
:
var vl = 5; //0101
var v2 = 15; //1111
var v3 = 0; //0000
print (vl & v2 ) ; //=>5 (0101)
print (vl &v3); //=>0 (0000)

print (vl v2 ); //=>10 (1010)
print (vl 1 ); //=>10 (1010)
print (vl > 1); //=>2 (0010)


, .
: true () false
(). . 50.5 .

50.5.

a == b . true,
. false

a != b . true,
. false

a === b ().
.
. b
, true. false

a !== b . .
.
, true.
false

a < b . true, .
false

a <= b . true,
. false

a > b . true, .
false

a >= b . true, .
false
50. 731

:
true==l // => true (true 1)
true===l // => false (true 1)
5 === "5" // => false ( "5" )
5 == "5" // => true ("5" )
5 > 4 // => true (5 4)
null == undefined // => true (null undefined)
null === undefined // => false (null undefined)


,
,
, ,
a[i]
. , new ...1
. +n
. -n
~n
!b
: j++


1-
var i = 8; I++1
var n = 11 + ++i * 9 % 5; ) -i
typeof obj
, . 50.1, n*n
Q) n/n
. , n%n
(++). ,

<> n+n
9. I n-n
S ni
: CD ni
n>i


var =11+9*9%5; n<n
n<=n
(*) (%) , n>n
n>=n

. , obj instanceofT
9*9. I
str in obj
: I n==n


S n!=n
var = 11 + 81 % 5; n===n

81 5 (%). n&n


: nAn

var = 11 + 1;
, 12.

. 50.1.

732 VII. Qt Script


. ,

, .
.
:
|| ;
&& ;

! .

if... else
.

. :
if ( )
[else ]
, else ,
- , false.
else
if. :
var = 3;
var b = 4;
if ( > )
print(" ");
else
print(" ");

, {}.
if else
if. :
if ( > b) {
//
}
else if( == b) {
//
}
else {
//
}
50. 733

switch
if...else switch.
.
switch :
switch () {
case 1:

[break]
case 2:

[break]

[default: ]
}

C/C++, .
.
, case.
.
case , , default, .
break, switch
. break ,
. ., break, case
default. value ,
num.
switch (num) {
case 1:
case "one":
value = "In
break;
case initialValue:
value = "0";
break;
default:
value = "unknown";
}


() ? :
if ,
. , ,
.
, if:
var = 3;
var b = 4;
var str = (a > b) ? " b" : " b";
print(str);
734 VII. Qt Script

.
, , , -
. , 0 100:
n = > 100 ? 100 : < 0 ? 0 : ;

.
break continue
- ,
. break,
.
continue ,
,
.

for
C/C++, Java Qt Script.
, .
for : ,
. :
for (; ; ) {

. ,
true, ,
.
:
var sum = 0;
for (var i = 1; i <= 10; ++i) {
sum = sum + i;

i 1 .
i 10. 10,
. i
sum.

while
while for, ,
. .
, for while.
.
50. 735

while :
while ( ) {

for while:
var sum = 0;
var i =1;
while (i <= 10) {
sum = sum + i;
++i;
}

do...while
do...while while. while
, .
:
do {

} while ( );
:
var sum = 0;
var i =1;
do {
sum = sum + i;
++i;
} while (i <= 10);

with
with
. , :
print(Math.PI);
print(Math.abs(-2));
print(Math.max(4, 10, 1, 6));

with:
with (Math) {
print(PI);
print(abs(-2));
print(max(4, 10, 7, 6));
}


, -
. ,
736 VII. Qt Script

, , ,
. .
, ,
, .

try...catch
,
, ,
catch. try...catch
:
try {

}
catch () {

}
final {

}

, try ,
.
catch . final ,
, .
. ,
File.
.
var file = new FileCfile.dat");
try {
file.open(File.Readonly);
}
catch(e) (
print("Code error:" + e);
}
finally {
file.close();
}

throw
throw
try...catch. ,
.
:
throw error;
50. 737

.

.
function.
. , :
function ([!][..., ])

[]
}

,
:
function multiply(varl, var2)
{
return varl * var2;
}

. ,
, .
:
var f = multiply(2.3, 13.7);
function ,
:
var myMultiplyFunction =
function multiply(varl, var2){ return varl * var2;};
var f = myMultiplyFunction(2.3, 13.7);
, Function
.
.
,
. :
var myMultiplyFunction =
new Function("varl", "var2", "return varl * var2;");
var f = myMultiplyFunction(2.3, 13.7);

, ,
arguments.
.
, ,
:
function multiply()
{
var result = 1;
for (var i = 0; i < arguments.length; ++i) {
738 VII. Qt Script

result *= arguments [i] ;


}

return result;
}

:
var f = multiply (34 . 5, 14.2, 8.7, 3.4, 7.1);

.
:
function factorial (n)
{
if ( (n == 0) II (n == 1) ) (
return 1;

else {
result = (n * factorial (n 1) ) ;
}
return result;
}
print ( "FactoriallO=" + factorial (10) ) ;

, var,
. ,
var, ,
. , ,
.
:
function food
{
m = 2;
}

foo ( ) ;
print (m) ; //=>2

m var,
,
.


Qt Script ,
. :
eval ( ) , Qt Script.
. , , ,

JavaScript . : eval ("for (var i = 0; i < 10;
++i) {print (i) ;}") ;
50. 739

isNaN ( ) true,
;
parseFloat ( ) .
;
parseint ( ) .
NaN.


Qt Script - . Qt Script
. ,
.
new. , ,
, .

Point () 50.1 ,
: , .
: _ _, . ,
this ,
(setxf) setY ( ) ) ( ( ) ()) . this
.

50.1.

function Point(, )
{
this.m_x = ;
this.m_y = ;

this.setx = function()

this.m_x = ;
}

this.setY = function()
{
this.m_y = ;
}

this.x = function!)
{
return this.m_x;
}

this. = function!)
(
return this.m_y;
740 VII. Qt Script

Point ( ) :
var pt = new Point (20, 30);
print ("X=" + pt.x() + ";Y=" + pt.yO);

: x=20;Y=30
, C++, JavaScript
| | . 50.1:
function Point (, )
{
this.m_x = || 0;
this.m_y = | | 0;
)

, :
var pt = new Point;,

0.
var pt = new Point (3);,

x 3, 0.
, , , :
this.m_str = str I I

, , private
C++, .
var ( 50.2).

50.2.

function Point (, ) {
this.m_x = ;
this.m_y = ;
var privateVariable = 8;
var privateMethod = function ( ) {
printout ( "private variable value:" + privateVariable);

this.setx = function (x)


{
privateMethod ( ) ;
this.m_x = x;
l

50.2 : privateVariable privateMethod))


. , pt
, :
Result of expression 'pt .privateMethod' [undefined] is not a function.
50. 741

. 50.2,
, setx ( )
.

. 50.1
( 50.3).

50.3.

var myPoint = {
m_x: 123,
m_y: 321,
x: function() {
return myPoint.m_x;
},
y: function() {
return myPoint.m_y;
}
}

print("X=" + myPoint.x() + Y=" + myPoint.());

: X=123,-Y=321


,
, . C++
static,
. JavaScript,
(. 50.3) .
50.4.

50.4.

Error = {
nrl: 'Can not read',
nr2: 'Can not write',
message: function() {
print('An error is occurred');

}
Error.message();
print(Error.nrl);

:
An error is occurred
Can not read
742 VII. Qt Script

,
call ( )
. ThreeDPoint.
, Point z ( 50.5).

50.5. Point

function ThreeDPoint(, , z)

Point.call(this, x, y);
this.m_z = z;

this.setz = function(z)
(
this.m_z = z;
}

this.z = function()
{
return this.m_z;
}
}

: , , z. this
call( ) Point. m_z
,
: setzo z().
:
var pt = new ThreeDPoint(20, 30, 40);
print("X=" + pt.x() + ";Y=" + pt.yO + ";Z=" + pt.zO);

: x=20;Y=30;z=40.
,
.
pt test ( ) ( ) ,
Point.
pt.test = function()
{
return "Test";
}

pt.x = function()
{
return -1;
)

print("X=" + pt.x() + "; " + pt.testO);

: x=-l; Test
50. 743

JavaScript (
50.6).

50.6. Point

function Point(, )
{
this.m_x = ;
this.m_y = ;
)
function ThreeDPoint(, , z)
{
this.base = Point;
this.base(x, y);
this.mz = z;
}
ThreeDPoint.prototype = new Point;
var pt = new ThreeDPoint(1, 2, 3);
print( "X=" + pt.m_x + ";Y=" + pt.m_y + ;Z=" + pt.m_z);

50.6 Point
z. : x=l;Y=2,-z=3.
,
m_z pt ,
:
delete pt.m_z;
, ,
hasOwnProperty(), :
pt.hasOwnProperty('m_z'); //=>true

instaceof
:
pt instanceof ThreeDPoint; //=> true
pt instanceof Point; //=> true
pt instanceof Date; //=> false

, , ,
typeof, :
typeof pt; //=> "object"
typeof "text"; //=> "string"

, Date (
50.7).

50.7.

Date.prototype.printFullYear = function!) {
print(this.getFullYear());
)
744 VII. Qt Script

var dt = new Date ( ) ;


dt .print Full Year ( ) ;

50.7 prototype
printFullYear . .
2014 .


,
. , - ,
( 50.8).

50.8.

function Point (, )
{
this.m_x = ;
this.m_y = ;
this.x = function ()
{
return this.m ;

var pt = new Point ( 1, 2 ) ;


printout ( "X=" + pt.x());

function myX()
{
return 1234;

pt .x = myX;
printout ( ,,X= + pt.x());

50.8 Point ()
. ( )
(). ()
1234.

JavaScript,
.


JavaScript ,
(JSON, JavaScript Object Notation). , JSON
XML,
50. 745

. ,
JavaScript, , ( 50.9).

50.9.
var json = ({
"name": "Piggy",
"phone": "+49 631322187",
"email": "piggy@mega.de",
"Details": {
"age": 47,
"lover": "Kermit",
"male": false,
"hobbies": ["Singing", "Dancing"],
"car": null

});
var jsonObj = eval(json);
var jsonDetailsObj = jsonObj.Details;
printout(jsonObj.name + " loves " + jsonDetailsObj.lover);

50.9
( . 40 41). json ,
eval().
{ ) . eval () ,
Details.
. : , .
( "name"), ( ""),
( "male"), ( "hobbies"), null ( "").

. 50.9
name lover. :
Piggy loves Kermit

. ,
50.9 (
):
jsonObj.getAge = function))
(
return jsonObj.Details.age;
}
printout(jsonObj.getAge());

47.

Qt Script C++ Java.


, :
.
51

Qt Script

,
.

Qt Script , C++
Java, , .
, -262, Qt Script
, , object,
Function, Array, String, Boolean, Number, Math, Date, RegExp,
EvalError, RangeError, ReferenceError, SyntaxError, TypeError URIError.
.

Global
, 50,
, Global.
.
, : object,
Number, String, Date ., eval(), isFiniteO, isNaN ( ) , parseFloat ( ) ,
parse into . ,
Qt-.

Number
Number .
: MAX VALUE MIN VALUE.
, isNaN () true.
,
, infinity,
isFinite ( ) ,
false.

Boolean
Qt Script , .
true false.
51. Qt Script 747

. , null, false,
NaN, undefined false,
true.

String
. string
.




lower( ) upper( ) , :
var str = new String("Test StRiNg");
print("LowerCase=" + str.lower()); //=> LowerCase= test string
print("UpperCase=" + str.upper()); //=> UpperCase= TEST STRING

replace( ) , :
var str = new String("QtScript");
var str2 = str.replace("Script", "5"); //str2="Qt5"


charAt().
:
var str = new String("QtScript");
var c = str.charAt(2); //c='S'


substring(),
. :
var str = new String("QtScript");
var str2 = str.substring(2, str.length); //str2="Script"

RegExp

.
4, , Qt Script. ,
:
.
748 VII. Qt Script

, #,
"/". :
var myRegexp = /([A-Za-z]+)=(\d+)/;
,
new. :
var myRegexp = new RegExp("([A-Za-z]+)=(\d+)");


,
exactMatch( ) :
myRegexp.exactMatch("myVar=l //Example"); //=> false
myRegexp.exactMatch("myVar=l"); //=> true



search ( ) searchRev ( ) ( , ):
myRegexp.search("var myVar=l //Example"); //=> 4

Array
Array , .
, , , C++ Java,
, Qt Script . ,
.
:
var arr = ["Evanescence", "Epica", "Xandria"];

new:
var arr = new Array("Evanescence", "Epica", "Xandria");
, . 51.1.

51.1.

Concat()
join()
()
push()

reverse()
shift()
slice()
51. Qt Script 749

51.1 ()


sort ( )
splice ( )
toSource ( ) ,
toString (
unshift ( )
unwatch ( )
watch ( )



:
var arr = ["Evanescence", "Epica", "Xandria"];
arr[3] = "Therion";
//arr=["Evanescence", "Nightwish", "Epica", "Therion"];
: push(),
, unshift (), , splice (),
.
,
, ,
, :
var arr = new Array("Evanescence", "Epica", "Xandria");
arr.splice(1, 0, "Therion", "Nightwish");
//arr=["Evanescence", "Therion", "Nightwish", "Epica", "Xandria"];


.
, :
var arr = new Array(2);
arr["first"] = "John";
arr["second"] = "Paul";
var firstBeatle = arr["first"];// firstBeatle=John
arr.second += " McCartney";
var secondBeatle = arr.second; // secondBeatle=Paul McCartney


reverse (),
:
var arr = ["Evanescence", "Epica", "Xandria"];
var arr2 = arr.reverse(); //arr2=["Xandria", "Epica", "Evanescence"]
750 VII. Qt Script

:
var arr2 = ["Evanescence", "Epica", "Xandria" ]. reverse () ;


join() ,
:
var arr = ["Evanescence", "Epica", "Xandria"];
var str = arr .join ("**") ; //str="Xandria**Epica**Evanescence"


concat ( ) :
var str = ["Evanescence", "Epica", "Xandria"];
var str2 = str .concat ( ["Therion", "Nightwish" ] ) ;
//=> str2=[ "Evanescence", "Epica", "Xandria", "Therion", "Nightwish"]


sort ( ) , :
var str = ["Xandria", "Evanescence", "Epica"];
var str2 = str.sortO; //=> str2=[ "Epica", "Evanescence", "Xandria"]


JavaScript
. .
, 3x3 :
var arr = [ [1, 1, 1] ,
[2, 2, 2],
[3, 3, 3] ] ;

:
var n = arr [0] [1] ;

3x3x3
:
[[[1, 1, 1],
[1, 1, 1],
[1, 1, 1]],
[[2, 2, 2],
[2, 2, 2],
[2, 2, 2]],
[[3, 3, 3],
[3, 3, 3],
[3, 3, 3]],
];
var n = arr[0][1][2];
51. Qt Script 751

Date
Date ( )
.
, , , , , .
,
, .

!
, ,
, 1 1970 .
1970 .

:
var moment = new Date(2014, 2, 6, 23, 55, 30);
var now = new Date();
getDateO.
: getYearO, getMonthO, getDayO, getHoursO, getMinutes(),
getseconds ( ) getMilliseconds ( ) , (
0), ( 0, 1 . .), , ,
.
, set.

.
getDay ( ):
var indexToDay = ["Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday"
];
var now = new Date();
print(indexToDay[now.getDay() 1] );

:
getDate ( ) ( 1 3 1);
getMonth ( ) ( 0 11);
getFuiiYear ( ) .
1900 + getYear ( ) ;
getHors ( ) ;
752 VII. Qt Script

getMinutes ( ) ;
getseconds() .
var month = ["January", "February", "March", "April", "Mai", "Jun",
"July", "August", "September", "October", "November",
"December"
];
var now = new Date;
var strDateTime = now.getDate() + ". "
+ month[now.getMonth()] + " "
+ now.getFullYear()+ " "
+ now.getHours()+ ":"
+ now.getMinutes()+ ":"
+ now.getSeconds();
printout(strDate);

:
22.January.2014 16:49:26

Math
Math ,
. .
(. 5 1.2).

51.2. Math

E E. (2,718281828459045)
LN2 2 (0,6931471805599453)
LN10 10 (2,302585092994046)
LOG2E 2 (1,4426950408889633)
LOG10E 10 (0,4342944819032518)
PI (3,141592653589793)
SQRT1 2 1/2 (0,7071067811865476)
SQRT2 2 (1,4142135623730951)

, Math.


abs ( ) .
. :
var xl = Math.abs(-123.5); //xl=123.5
var x2 = Math.abs(123); //x2=123
51. Qt Script 753

Math : ceil(), floor () round(). ceil()


, .
, . :
var xl = Math.ceil(5.2); //xl=6
var 2 = Math.ceil(-5.5); //2=-5
var = Math.ceil(6); /7x3=6

floor ( ) ,
.
var xl = Math.floor(-5.4); //xl=-6
var 2 = Math.floor(5.9); //2=5
var = Math.floor(6); //=6

round () :
var xl = Math.round(5.4); //xl=5
var x2 = Math.round(5.5); //x2=6
var x3 = Math.round(6); //x3=6


max ( ) ,
. ,
. :
var xl = Math.max(5.4, 5.5); //xl=5.5
var x2 = Math.max(10, 2, 5, 3); //x2=10

min(),
. .
var xl = Math.min(5.4, 5.5); //xl=5.4
var x2 = Math.min(10, 2, 5, 3); //x2=2


pow ( ) : ( ,
), . :
var = Math.pow(2, 3); //=8


sqrt ( ) 72.
, pow ( ) ,
sqrt ( ) .
var = Math.sqrt(2); //=1.414213562373095

, NaN.
754 VII. Qt Script


random ,
0 1.
, :
function randomize(range)
{
return (Math.random() * range)

print(randomize(1000));


.
( cos ), ( sin())
( tan() ). . ,
, .
180. ,
270 (-90 )
:
var rad = -90 * Math.PI / 180;
print(Math.sin(rad)); //=> -1

, , ,
. Math , ,
:
function ctg(angle)
{
return Math.cos(angle) / Math.sin(angle);
)

Math :
(acosO), (asinf)) (atano). ,
-1 :
print(Math.asin(-1) / Math.PI * 180); //=> -90


log ( ) :
var = Math.log(Math.E); // x=l
Qt Script , ,
:
function loglO(arg)
{
return Math.log(arg) / Math.LNIO;
)
var x = logl0(10); // x=l
51. Qt Script 755

Function
50.
.
.
, ,
:
var myJoin =
new Function("a", "b", "c", "sep", "return a + sep + b + sep + c");
print(myJoin("Therion", "Epica", "Nightwish", "**"));
//=> Therion**Epica**Nightwish

,
Function ,
,
.

, Qt Script.

, , .
52

Qt Script

:
?
!

, ,
C++. Qtscript
Qt- (
49):
QScriptvalue Qt Script;
QScriptContext Qt Script;
QScriptEngine ,
Qt Script.

QScriptValue
, -262: Undefined, Null,
Qt Script :
Boolean, Number, String object.
Variant QObject.

QScriptvalue .
1ST() : isBooleanO,
isstringo, isArrayO . . toT ( )
: toString ( ) , toBoolean ( ) , toNumber ( ) . .

QScriptContext
, .
C++ ,
. , :
fct(3, "Text")

QScriptContext,
3, "Text".
argument ( ) , .
argumentCount ( ) .
52. Qt Script 757

QScriptEngine
QScriptEngine Qtscript. Qt-,
, .
, . -
QScriptEngine::evaluate(),
QScriptvaiue. :
QScriptValue value = engine.evaluate("5 * 5");
int number = value.toInt32(); //number=25

isError ()
QScriptValue. :
QScriptValue value = engine.evaluate("script error test");
if (value.isError()) {
//
qDebugO value.toString();
}

QScriptEngine newT ( ) :
newDate(), newRegExp . .
Qt ,
newQObject . QObject
. , ,
.
.
.
giobaiobjecto.

. :
QScriptValue mylnt = QScriptValue(SscriptEngine, 2007);
engine.globalObject ().setProperty("mylnt", mylnt);

, ,
, , .
,
Q_DECLARE_METATYPE. ,
QVector<float>, QColor QstringList, - :
Q_DECLARE_METATYPE(QVector<float>)
Q_DECLARE_METATYPE(QColor)
Q_DECLARE_METATYPE(QStringList)

, C++,
:
QScriptValue myFunction(QScriptContext*, QScriptEngine*)

,

( 52.1).
758 VII. Qt Script

52.1.

QScriptValue getWidgetByName(QScriptContext* pcontext,


QScriptEngine* pengine
)
{
QString strName = pcontext->argument(0).toString();
QObject* pobj = 0;
foreach (QWidget* pwgt, QApplication::topLevelWidgets()) {
if (strName == pwgt->objectName()) {
pobj = pwgt;
break;
}
else if (pobj = pwgt->findChild<QObject*>(strName)) {
break;

return pengine->newQObject(pobj);
}

getWidgetByName ( ) , 52.1,
. QScriptContext : : argument ( )

.
QScriptvalue::toString ( )
strName. foreach .
, ,
findChiid<T> ( ) .
,
:
QScriptValue fct = engine.scriptValue(getWidgetByName);
engine.globalObject ().setProperty("getWidgetByName", fct);

getWidgetByName)) .
, mywidgetl
:
var wgt = getWidgetByName('mywidgetl');

52.1 ,
QObject, newObjecto
QScriptValue . ,

, ? newvariant ( ) . 52.2
.

52.2.

QScriptValue toUpper(QScriptContext* pcontext,


QScriptEngine* pengine
)
52. Qt Script 759

{
QString str = pcontext->argument (0) .toString () ;
return pengine->newVariant (str .toUpper ( ) ) ;
}

, newArrayf). 52.3
,
.

52.3.

QScriptValue getFileNames(QScriptContext* pcontext,


QScriptEngine* pengine
)
{
QString strDir = pcontext->argument(0).toString();
QString strExt = pcontext->argument(1).toString();
QDir dir(strDir);

QStringList 1st = dir.entryList(strExt.split(" "), QDir::Files);

QScriptValue sv = pengine->newArray(1st.size());
for (int i = 0; i < 1st.size(); ++i) {
sv.setProperty(i, QScriptValue(pengine, 1st.at(i)));
}

return sv;
)

, ,
QScriptValue, 52.4.

52.4.

QScriptValue myMessage(QScriptContext* pcontext,


QScriptEngine* pengine
)
{
qDebugO "MyMessage";
return pengine->nullValue();
)


, ,
. ,
.
760 VII. Qt Script


, , ,
Logo. .
,
. , ,
.
( 52.5-52.10)
(. 52.1).

Evaluate (). :
forward() ;
back() ;
left(nAngle) nAngle;
right(nAngle) nAngle;
reset ( ) .

. 52.1.

, 52.5,
.

52.5. main.cpp. main()

#include <QApplication>
#include "TurtleWorkArea.h"
52. Qt Script 761

int main(int argc, char** argv)


{
QApplication app(argc, argv);
TurtleWorkArea turtleWorkArea;
turtleWorkArea.show();

return app.exec();
)

52.6 Turtle,
. : m pix m painter.
, .
, .
:
400x400. (m_painter)
(m_pix),
.
QWidget: : setFixedSize . -,
, ,
QWidget::paintEvent () QPainter: : drawPixmap ( ) ,
.
1:1, ,
.
init ( ) . init( ) , ,
QPixmap: : fill .
QPainter: : translate
. QPixamp: : rotated
90 .
, .
, .
forward ( )
.
, QWidget: : repaint .
back() , , .
left righto
nAlpha .
reset ( ) .
. QPainter::resetMatrix(),
.
init ( ) , ,
.
QWidget : : repaint ( ) .

52.6. Turtle.h.

#pragma once

#include <QtWidgets>
#include <math.h>
762 VII. Qt Script

// =================================
class Turtle : public QWidget {
--
Q_OBJECT
private:
QPixmap m_pix;
QPainter m_painter;

public:
Turtle(QWidget* pwgt = 0) : QWidget(pwgt)
, m_pix(400, 400)
, m_painter(&m_pix)
(
setFixedSize(m_jpix.size());

init();
}

protected:
void init()
{
m_pix.fill(Qt::yellow);
m_painter.translate( rect().center());
m_painter.rotate(-90);
l
virtual void paintEvent(QPaintEvent*)
(
QPainter painter(this);
painter.drawPixmap(rect(), m_pix);
}

public slots:
void forward(int n)
(
m_painter.drawLine(0, 0, n, 0);
m_painter.translate(n, 0);
repaint();
}

void back(int n)
{
m_painter.drawLine(0, 0, -n, 0);
m_painter.translate(-n, 0);
repaint();
}

void left(int nAngle)


{
m_painter.rotate(-nAngle);
}
52. Qt Script 763

void right (int nAngle)


{
m_painter.rotate(nAngle);
}

void reset ()
t
m_painter.resetMatrix();
init();
repaint();
}

,
.
TurtleWorkArea, 52.7. :
( m ptxt),
(m scriptEngine) ( m_pTurtle).

52.7. TurtleWorkArea.h.
#pragma once

#include <QWidget>
#include <QScriptEngine>

class QTextEdit;
class Turtle;

// --------------------
---
--- -------- ===========
class TurtleWorkArea : public QWidget {
============

Q_OBJECT
private:
QTextEdit* m_ptxt;
QScriptEngine m_scriptEngine;
Turtle* m_pTurtle;

public:
TurtleWorkArea(QWidget* pwgt = 0);

private slots:
void slotEvaluate ( );
void slotApplyCode(int);
};

( 52.8)
m pTurtie
. : Haus vom Nikolaus ( ), Curly (), Circle (
) Fantasy (). slotApplyCode ( ) ,
activatedt),
764 VII. Qt Script

. slotApplyCode ( ) .
newQObjectO QScriptEngine
. ,
QScriptvalue.
QScriptvalue::setProperty ( ) ,
, .


newQObjectO
. ,
QWidget,
:
pengine->newObject(m_pTurtle,QScriptEngine::ScriptOwnership,
QScriptEngine:: ExcludeSuperClassContents).

( pcmd),
, .
slotEvaluate ( ) .
.

52.8. TurtleWorkArea.cpp.

TurtleWorkArea::TurtleWorkArea(QWidget* pwgt/*=0*/) : QWidget(pwgt)


{
m_pTurtle = new Turtle;
m_pTurtle->setFixedSize(400, 400);
m_ptxt = new QTextEdit;

QComboBox* pcbo = new QComboBox;


QStringList 1st;

1st "Haus vom Nikolaus" "Curly" "Circle" "Fantasy";


pcbo->addIterns(1st);
connect(pcbo, SIGNAL(activated(int)), SLOT(slotApplyCode(int)));
slotApplyCode(0);

QScriptvalue scriptTurtle =
m_scriptEngine.newQObject(m_pTurtle);
m_scriptEngine.globalObject().setProperty("turtle", scriptTurtle);

QPushButton* pcmd = new QPushButton("SEvaluate);


connect(pcmd, SIGNAL(clicked()), SLOT(slotEvaluate()));

QGridLayout* pgrdLayout = new QGridLayout;

pgrdLayout->addWidget(pcbo, 0, 0);
pgrdLayout->addwidget(m_ptxt, 1, 0);
pgrdLayout->addwidget(m_pTurtle, 0, 1, 2, 1);
pgrdLayout->addwidget(pcmd, 2, 0, 1, 2);
setLayout(pgrdLayout);
52. Qt Script 765

slotEvalute () , 52.9, QTextEdit::toPlainText()


, ,
QScriptEngine::evaluate () .
if isError().
.

52.9. TurtleWorkArea.cpp. slotEvaluateO

void TurtleWorkArea::slotEvaluate()
{
QScriptValue result =
m_scriptEngine.evaluate(m_ptxt->toPlainText());
if (result.isError()) {
QMessageBox::critical(0,
"Evaluating error",
result.toString(),
QMessageBox::Yes
);

slotApplyCode () , 52.10,
, .
.
, .

52.10. TurtleWorkArea.cpp. slotApplyCode ()

void TurtleWorkArea::slotApplyCode(int n)
{
QString strCode;
switch (n) {
case 0:
strCode = "var k = 100;\n"
"turtle.reset();\n"
"turtle.right(90);\n"
"turtle.back(-k);\n"
"turtle.left(90);\n"
"turtle.forward(k);\n"
"turtle.left(30);\n"
"turtle.forward(k);\n"
"turtle.left(120);\n"
"turtle.forward(k);\n"
"turtle.left(30);\n"
"turtle.forward(k);\n"
"turtle.left(135);\n"
"turtle.forward(Math.sqrt(2)*k);\n"
"turtle.left(135);\n"
"turtle.forward(k);\n"
766 VII. Qt Script

"turtle.left(135);\n"
"turtle.forward(Math.sqrt(2)*k);\n";
break;
case 1:
strCode = "turtle.reset();\n"
"for (i = 0; i < 2; ++i) {\n"
for(j = 0; j < 100; ++j) {\n"
" turtle.forward(15);\n"
" turtle.left(100
j);\n"
" }\n"
" turtle.right(180);\n"

break;
case 2:
strCode = "turtle.circle = function!)\n"
{\n"
" for (var i = 0; i < 360; ++i) {\n"
" this.forward(1);\n"
" this.left(1);\n
" }\n"
"}\n"
"turtle.reset();\n"
"turtle.circle();\n";
break;
default:
strCode = "turtle.reset();\n"
"for (i = 0; i < 200; ++i) {\n"
" turtle.forward(i * 2);\n"
" turtle.left(91);\n"

}
m_ptxt->setPlainText(strCode);

, 52.10:
switch (case ) .
, ,

;
switch (case l) ;
(case 2) . ,
circle () .
Qt Qt Script;
switch (default) .
91 left () 120, .
171 , 160
, 181 , 45 , 115 ,
31 . , - ,
, !
52. Qt Script 767

,
, ,
. !
Qt-.
Qt-, ,
.
, connect ( )
, . , ,
clicked( ) buttonciicked():

function buttonciicked()
{
print("The button " + this.text + " was clicked");
}
cmd.clicked.connect(buttonPressed);

, , clicked, cmd,
this.
, .
, connect ( )
disconnect . :
cmd.clicked.disconnect(buttonciicked);
( 52.11 52.12)
: Qt-,
(. 52.2). .

. 52.2.

, 52.11,
wgt.
setobjectName , .
, (wgt)
. : ( ptxt)
( pibll, 12 1).
wgt
show ( ) . script.js,
, .
wgt "wgt",
evaluate ( ) , , 52. 12. -
768 VII. Qt Script

QScriptvalue, ,
.

52.11. . main.cpp

#include <QtWidgets>
#include <QtScript>

int main(int argc, char** argv)


{
QApplication apptargc, argv);
QWidget wgt;

QLineEdit* ptxt = new QLineEdit;


ptxt->setObjectName("lineedit");

QLabel* plbll = new QLabel("1");


plbll->setObjectName("labell");

QLabel* plbl2 = new QLabel("2");


plbl2->setObjectName( "label2");

QLabel* plbl3 = new QLabel("3");


plbl3->setObjectName( "label3");

//Layout Setup
QVBoxLayout* pvbxLayout = new QVBoxLayout;
pvbxLayout->addWidget(ptxt);
pvbxLayout->addwidget(plbll);
pvbxLayout->addWidget(plbl2);
pvbxLayout->addwidget(plbl3);
wgt.setLayout(pvbxLayout );

wgt.show();

//Script part
QScriptEngine scriptEngine;
QFile file(":/script.js");
if (file.open(QFile::Readonly)) {
QScriptvalue scriptWgt = scriptEngine.newQObject(swgt);

scriptEngine.globalObject().setProperty("wgt", scriptWgt);

QScriptvalue result =
scriptEngine.evaluate(QLatinlString(file.readAll()));
if (result.isError()) {
QMessageBox::critical(0,
"Evaluating error",
result.toString(),
QMessageBox::Yes
);
52. Qt Script 769

}
}
else {
QMessageBox::critical(,
"File open error",
"Can not open the script file",
QMessageBox::Yes
);
}
return app.exec();
}

, 52.12, MyClass,
updateText ( ) label, ,
. updateText ( )
label .
( text) , .
updateText ( ) , ,
, labell.
wgt windowsTitle
"Signal And Slots". text
"Test". textchanged
updateText () .
.
myObject MyClass,
112 updateText ( ) textchanged. ,
"updateText". updateText
this , connect().
,
myObject. ,
:
wgt.lineedit.textchanged.connect(myObject, myObject.updateText);

Qt ,
connect ( ) (label3)setText().
, ,
(. . 52.2).

52.1,
-.
( wgt), (. 52.8).

52.12. Qt Script. scriptjs

function MyClass(label)
{
this.label = label
770 VII. Qt Script

MyClass.prototype.updateText = function(str)
{
this.label.text = str;
}

function updateText(str)
{
wgt.label1.text = str;
}

wgt.windowsTitle = "Signal And Slots";

wgt.lineedit.text = "Test";
wgt.lineedit.textChanged.connect(updateText);

var myObject = new MyClass(wgt.Iabel2);


wgt.lineedit.textChanged.connect(myObject, "updateText");

wgt.lineedit.textChanged.connect(wgt.Iabel3.setText);

Qt Script
, QtScriptTools.
(*.) Qt QtScript.
QT += script scripttools


: _FILE_ _LINE_.
, ,
.

QScriptEngineDebugger.
( 52.13)
(. 52.3).
( 52.13)
QScriptEngine QScriptEngineDebugger.
, attachTo ( )
( scriptEngine).
,
debugger ,
.
,
QScriptEngineDebugger::interruptAction ,
action().

, ,

.
52. Qt Script 771

. 52.3. Qt Script

,
trigger().
, sum.

52.13.

#include <QtWidgets>
#include <QtScript>
#include <QScriptEngineDebugger>

int main(int argc, char** argv)


{
QApplication app(argc, argv);

QScriptEngine scriptEngine;
QScriptEngineDebugger scriptDebugger;

scriptDebugger.attachTo(&scriptEngine);

QAction* pact =
scriptDebugger.action(QScriptEngineDebugger::InterruptAction);
pact->trigger();
772 VII. Qt Script

QString strCode = "var sum = 0;\n"


"for (var i = 1; i < 5; i++) {\n"
" sum += i;\n"

QScriptValue result = scriptEngine. evaluate (strCode) ;


return app . exec ( ) ;
}

Step Into ( *] ), Step Over Step Out ( ),


(. . 52.3), ,
Locals sum i.

,
, . ,


. .
.
Breakpoints.
Console ,
. ,
, ,
. . 52.1.

52.1.


. advance . : .advance
myscript. js:14

.backtrace
.break . : .break 14
.clear . : .clear 14
. condition . :
.condition 1 i < 5

. continue
.disable .
(ID), : .disable 34
.down

. enable ( ).
(ID), : .enable 34

.eval , : .eval myscript. js


. finish

.list , :
.list myscript . js : 34
52. Qt Script 773

52.1 ()


.info breakpoint
.info locals ,

.interrupt
.next ,
. : .next count=3
.up


, .
widget ( ) .
, , ,
:
QWidget* pConsole =
pDebugger->widget (QScriptEngineDebugger : :ConsoleWidget) ;
QWidget* pStack =
pDebugger->widget (QScriptEngineDebugger: : StackWidget) ;
pConsole->setStyle (QStyleFactory: : create ("QFusionStyle") ) ;
pStack->hide ( ) ;

Qt-,
.
, Qt Script.
QScriptEngine,
Qt Script .
. ,
, Qt Script,
Qt-.
QtScriptTools ,
.
VIII

Qt Quick

.
. .

53. Qt Quick
54.
55.
56.
57.
58.
59. /
60. Qt Quick C++
53

Qt Quick

,
,
.

Qt Quick , ,
, ,
, . ,
.
:

QML ;
Qt , ;
JavaScript .
50 51 ',
Qt Creator (. 47).

?
, , - ,
, Qt ,
. ,
.
, ,
, . QML (Qt Meta-Object Language, -
Qt) .
QML, ,
,
. (Rapid Prototyping)
. , QML
. ,
,
.
,
, . C++
, , , ,
778 VIII. Qt Quick

1 ,
.
, Adobe Flash,
Adobe Flash C++ .
, .
QML,
,
, .
, , ,
, , ,
.
Qt Quick ,
, Qt,
.
. , ,
, ,
. ,
, Qt (
Qt- 22).
, Qt Quick ,
.
, ,
. ,
.
.
,
QML JavaScript, C++, C++,
, . ,

, . ,
,
, .
,
: Windows, Mac OS X Linux,
, ,
. ,
Web- , Qt Quick Web-:
, ,
,
.
, Qt Quck-.
, , qmlviewer, Qt.
. ,
, ,
, . ,
Qt Quick, .


( . perfection ) ,

. .
53. Qt Quick 779

, BlackBerry, ,
Qt Quick BlackBerry 10
Cascades .
, Qt Quick , ,
Qt Quick, C++.
, ? !

QML
QML (Qt Meta-Object Language, -
Qt), Qt Quick.
QML , ,
.

, . - ,
. ,
QML JavaScript. Web-
, , AdobeFlash,
QML.

C++ - , ,
, ,
QML, , ,
. . QML
, , , ,
. ,
.
.
QML Qt , ,
Qt/C++, QtwebKit, QtMobility,
, , (invokable methods),
Q_INVOKABLE . . QML .
Qt Creator .


QML
Qt Creator (. 47). , ,
(Qt Creator : http://qt-project.org).
, , ,
QML.
, . 53.1.
Qt Quick-:
Qt Quick QML C++;
Qt Quick QML
qmlviewer;
780 VIII. Qt Quick

QML QML
C++.

Qt Quick ...,

. 53.1. Qt Quick

(. 53.2), HelloQML.
, QtQuick 1.1
. Qt Creator QML-
, 53.1.

53.1. QML-

import QtQuick 1.1

Rectangle {
width: 360
height: 360
Text {
anchors.centerln: parent
text: qsTr("Hello QML")
}
53. Qt Quick 781

MouseArea {
anchors.fill: parent
onClicked: {
Qt.quit();
}
}
}

P Qt Quick

ie 11 ! ie

Qt Quick.

: HelloQMlJ

: C:\Users\alina ,
[

. 53.2. Qt Quick

! QML-. import.
, .
C++ include.
QtQuick, .
QtQuick . ,
, , 1 .1,
. ,
QML-
, .
.
Rectangle (),
360 . . QML
, ,
. ,
: name: value. Rectangle
width height,
Text anchors.centerln text, MouseArea anhors.fill
onClicked. JavaScript,
onClicked.
782 VIII. Qt Quick

, C++: /* ... */ //.


, , ,
, .
, JavaScript, ,
,
.
,
. , Qt Creator.
Hello QML,
.

Qt Creator.
Qt Quick-. ,
, ,
QML. :
QML-;
,
;
QML;
, QML-
JavaScript ;
.
:
<Alt>+<Space> ;
<Ctrl>+<Space> , ;
, ,
, ,
, , (. 56);
(. 53.4),
QML- .
,
, .
QML-,
,
.
53. Qt Quick 783

main.qml - HelioQML - Qt Creator


Navigator w main X Properties x
Rectangle Type
% PT Text
Welcome
Type Text

Id
Geometry
Position X 147.0 C v 172.0
Sire W 65.0 H 16.0

Visibility
Visibility Is visible Smooth
clip

Opacity 1.0 C
Layout Advanced
A U

Style 000000

Border Image

HelioQML
Flickable
> A 255
4.8.0 Debug $
Flipable r Text

=
Text HelioQML

V Wrap Mode NoWrap

> 1
Focus Scope

P' Over 1 2 1 3 4

. 53.4. QML

Qt Creator
,
, QML-. ,
import, , Qt Creator
.
Qt Creator !

JavaScript QML
, QML ,
, QML .
- . ? QML
JavaScript.
.
JavaScript,
width Rectangle:
Rectange {
width: parent. width / 5
}

JavaScript ,
.
,
width:
784 VIII. Qt Quick

Rectangle {
width: {
var w = parent.width /5
consloe.debug("Current width:" + w)
return w

JavaScript .
:
Rectangle {
function maximum(a, b)
{
return a > b ? a : b;
}
width: maximum(parent.width, 100)
}

JavaScript
QML- .
myfunctions.js.
QML-:
import "myfunctions.js" as MyScripts
Rectangle {
function maximum(a, b)
{
return a > b ? a : b;
}
width: MyScripts.maximum(parent.width, 100)

import as MyScripts
, ,
. ,
,
.
,
QML- .
myfunctions.js, JavaScript-,
:
.pragma myfunctions
,
QML.

Qt Quick
. ,
, , .
53. Qt Quick 785

Qt Quick
, . Qt Quick
QML. , , ,
. QML
, .
QML,
, .
Qt Quick JavaScript
Web- QML
.
QML ,
C++. , QML ,
Qt, : ,
.
Qt Quick , ,
,
.
Qt Creator ,
, QML-
, .
54

,
.
, , , .

,
QML. . .
, . . ,
. , ,
, . .
.


:
item . item
QWidget Qt. item , ,
. , ,
, . . ;
Rectangle
;
image ;
Border image ;

Listview ;

Gridview ;

Text ;

Webview , Web-.
, .
. QML , Qt,
, .
Rectangle item ( 54.1).
, (. 54.1).
54. 787

. 54.1.

54.1 item
, 360x360 width
height. Rectangle
: 100 : 50 ( ) 170x200 ( width
height). color : "darkkhaki".

54.1.

import QtQuick 2.2


Item {
width: 360
height: 360
Rectangle {
color: "darkkhaki"
x: 100
y: 50
width: 170
height: 200
}
}

54.1, QML,
.
border.color, radius smooth
(),
. :
Rectangle {

border.color: "black
788 VIII. Qt Quick

radius: 5
smooth: true


,
.
. :
, , position ;
width, height ;
anchors (. 55);
id, parent .
54.1.
. .
C++ , QML ,
, .
,
.
id ,
. ,
id .

, id ,
,
.


parent .
( 54.2 54.3)
parent id ,
parent, id (. 54.2).
54.2 .
redrect ( id), ( color), 0, 0 (
). ( width height)
.
parent .
( color)
, ,
redrect.
( width height).
, ,
. ?
,
, QML , ,
, .
54. 789

. 54.2. id parent

, , .
QML , ,
,

(onwidthchanged, onHeightChanged . .).
, , .

54.2. parent id

import QtQuick 2.2


Item {
width: 360
height: 360
Rectangle {
id: redrect;
color: "red"
x: 0
y: 0
width: parent.width / 2
height: parent.height / 2

Rectangle {
color: "green";
x: redrect.width
y: redrect.height
width: redrect.width
height: redrect.height
790 VIII. Qt Quick

54.3 onWidthChanged onHeightChanged


. .
, JavaScript,
.

54.3.

import QtQuick 2.2


Item {
width: 200
height: 200
Rectangle {
width : parent . width
height : parent . height
onWidthChanged: {
console. log ("width changed:" + width)
}
onHeightChanged: {
console. log ("height changed:" + height)

}
}


, ,
. property,
:
property <> <>[: <>]
,

.
. . 54.1
.

54.1.


action qaction
bool , false true
color
date YYYY-MM-DD
int
list
real
string
time HH:MM:SS
54. 791

54.1 ()

url , URL (Uniform Resource Locator,


)
vercor3d -, - z-

( 54.4) ,
Text,
(. 54.3).

Element
1
3.14159
true
http://www.bhv.com/

. 54.3.

54.4 myelement item


. Text
text.
,
. ,
myelement onConditionChanged,
condition:
onConditionChanged: {
//do something
}

54.4.

import QtQuick 2.2


Item {
width: 200
height: 200

Item {
id: myelement
property string name: "My Element"
property int ver: 1
property real pi: 3.14159
property bool condition: true
property url link: "http://www.bhv.com/
}

Text {
x: 0
: 0
792 VIII. Qt Quick

text: myelement.name + "<br>"


+ myelement.ver + "<br>"
+ myelement.pi + "<br>"
+ myelement.condition + "<br>"
+ myelement.link

onx- Qt Creator
.


.
, .
, . ,
, ,
.
, ,
components , :
import "../components"
components ,
:
import "http://www.maxschlee.com/qml/components
( 54.5 54.6) ,
, Rectangle (. 54.4).
Qt Creator.
TextField.qml, ,
main.qml.

TextField
Text Text Text
Text Text Text

. 54.4.

54.5
Rectangle, Text.
. Text.
. ,
Rectangle.
(alias)
.
. - text Rectangle
54. 793

txt, text Text.


.
, width Rectangle .
, .

.
. ,
. ,
.
Rectangle Text.
( ) ,
Rectangle.

54.5. . TextField.qml

import QtQuick 2.2


Rectangle {
property alias text: txt.text
property string name: "TextField"

width: txt.width
height: txt.height

Text {
id: txt
x: 0
: 0
}
}

54.6 TextField.
TextField.qml , main.qml,
. : 10 : 20 (
). ( color).
text , ,
, . , , ,
( border.width).

54.6. . main.qml

import QtQuick 2.2


Item {
width: 150
height: 100

TextField {
x: 10
y: 20
color: "yellow"
794 VIII. Qt Quick

text: "Text Text Text<br>Text Text Text"


border .width: 1
}
}



Qt Quick ,
.
, II . ,
,
. ,
QML- QtQuick. Controls.
( 54.7) (. 54.5).

. 54.5.

54.7 QtQuick. Controls.


Applicationwindow. 320x240.
, , show ( ) , QML
visible true.
title.
Button . text
"Quit" , width
height. onClicked
Qt . quit ( ) .

54.7. . main.qml

import QtQuick 2.2


import QtQuick. Controls 1.2

Applicationwindow {
width: 320
height: 240
visible: true
title: "One Button"

Button {
text: "Quit"
width : parent . width
54. 795

height: parent.height
onClicked: Qt.quitO;
}
}

. 54.2 , QtQuick.Controls.

54.2. Qt Quick


Busylndicator
Button
Calendar
CheckBox
ComboBox
GroupBox
Label
ProgressBar
RadioButton -
ScrollView
Slider
SpinBox
SplitView
Stackview
Switch
TableView
TabView
TextArea
TextField
ToolButton
ExclusiveGroup ,

( 54.8), . 54.6,
, ProgressBar Slider (. . 54.2).
File Quit
.
54.8, (. 54.7),
QtQuick.Controls ApplicationWindow.
.
MenuBar, Menu :
"File". Menuitem .
796 VIII. Qt Quick

. 54.6. ,

, .
text "Quit" : onTriggered.

ProgressBar Slider. , , width, height
ProgressBar
value value,
slider.
slider
, , width, height .
0.75, tickmarksEnabled
0.1 ( steps ize).
Application
( statusBar) ( ToolBar).

54.8. , .
main.qml
import QtQuick 2.2
import QtQuick. Controls 1.1

ApplicationWindow {
visible: true
width: 200
height: 75
title: "Controls"

menuBar: MenuBar {
Menu {
title: "File"
Menultem {
text: "Quit"
onTriggered : Qt . quit ( ) ;
}
}
}

ProgressBar {
x: 0
y: 0
width : parent . width
54. 797

height: parent .height / 2


value: slider. value
}
Slider {
id: slider
x: 0
y: parent .height /2
.
width : parent width
height: parent .height / 2
value: 0.75
tickmarksEnabled: true
stepSize: 0.1


Qt Quick
ColorDialog, FileDialog, FontDialog
Mess age Dial .

QtQuick. Dialogs.
( 54.9)
. (. 54.7)
Click to start a color dialog
, .
,
,
, .

Dialoas Demo n
Co,ors

Cancel

. 54.7.
798 VIII. Qt Quick

54.9 QtQuick. Dialogs


Button. onClick

visible false true
.
ColorDialog
colorDialog, visible true .
modality


.
. Qt windowModal, .
title color
. , onAccepted.
(
informat iveText)
( visible).
visible MessageDialog
false .
, modality Qt.NonModal.
,
, .

54.9. . main.qml

import QtQuick 2.2


import QtQuick. Controls 1.2
.
import QtQuick Dialogs 1 1.
ApplicationWindow {
width: 200
height: 100
visible: true
title: "Dialogs Demo"

Button {
width: parent. width
height : parent . height
text: "Click to start a color dialog"
onClicked: {
messageDialog .visible = false;
colorDialog. visible = true;
}
}

ColorDialog {
id: colorDialog
visible: false
modality: Qt .WindowModal
title: "Select a color"
54. 799

color: "blue"
onAccepted: {
messageDialog.informativeText = "Selected color: " + color
messageDialog.visible = true
}
}

MessageDialog {
id: messageDialog
visible: false
modality: Qt.NonModal
title: "Message"

QML.
, , ,
.
, , ,
, .
.
, .
,
JavaScript.
Qt Quick
, , II.
Qt Quick , , ,
.
55

, QML ,
, , Qt, ,
, . , ,
,
,
.
QML, , ,
.

(anchor) .
.

.
, . 55.1 ( 55.1).
QML , . .
, .
( 55.1) Text Rectangle,
Text Rectangle,
. parent anchors.centerin
Text. . 55.2 .

55.1.

import QtQuick 2.2


Rectangle {
width: 360
height: 360
Text {
text: "Centered"
anchors.centerin: parent
55. 801

, . 55.2, ,
verticalCenter horizontalCenter ( 55.2).
, . 55.1.

horizontalCenter ::

left right
e
.top
t t
( I


*
_iccccucc
*




II

((((1(1 icccccccii

verticalCenter




*
(((,((((((( bottom
4 4
4 L

. 55.1. . 55.2.

55.2.

import QtQuick 2.2


Rectangle {
width: 360
height: 360
Text {
text: "Centered"
anchors.horizontalCenter: parent.horizontalCenter
anchors.verticalCenter: parent.verticalCenter
}
}


, ,
parent.horizontalCenter, parent.anchors.horizontalCenter.

,
. , -
, ?
, 55.3.

55.3.

import QtQuick 2.2


Rectangle {
width: 360
height: 360
Text {
text: "Text
802 VIII. Qt Quick

anchors.left: parent.left
anchors.right: parent.right
anchors.top: parent.top
anchors.bottom: parent.bottom

anchors fill,
(. 55.3) .
. ,
55.4 55.3.

55.4.

import QtQuick 2.2


Rectangle {
width: 360
height: 360
Text {
text: "Text"
anchors.fill: parent
}
}

55.3 . ,
, .
,
,
anchors.
C++. ,
. ,
QML .
. 55.3
anchors :
anchors {
left: parent.left
right: parent.right
anchors.top: parent.top
anchors.bottom: parent.bottom
}

, ,
( 55.5).

55.5.

import QtQuick 2.2


Rectangle {
width: 360
height: 360
55. 803

Rectangle {
color: "lightgreen"
anchors.fill: text
}

Text {
id: text
text: "Text"
anchors.fill: parent

,
.
fill, , ,
, - .
, -
(. 55.3).
, -
, , . .
, .
55.3
.

. 55.3.

55.5 55.1: anchors.centerin:


parent. -
, (. 55.4).
, anchors
. ( 55.6)
(. 55.5).
55.6 redrect ,
. ( width height) ,
. , -
804 VIII. Qt Quick

( opacity) .
( top) ( verticalCenter)
. ( bottom) .
( left) (

horizontaicenter) , ( right)
.

55.6.

import QtQuick 2.2


Item {
width: 360
height: 360

Rectangle {
id: redrect
color: "red"
width: parent.width / 1.5
height: parent.height / 1.5
anchors.top: parent.top
anchors.left: parent.left
}
Rectangle {
opacity: 0.5
color: "green"
anchors.top: redrect.verticalCenter
anchors.bottom: parent.bottom
anchors.left: redrect.horizontalCenter
anchors.right: parent.right
55. 805

,
, .
. 55.6 . ,

( 55.7).

. 55.6.

55.7 : ,
. 60 100.
( ) redrect greenrect,
.
left right right
left .
,

.

55.7.

import QtQuick 2.2


Item {
width: 360
height: 60

Rectangle {
id: redrect
color: "red"
anchors.left: parent.left
anchors.top: parent.top
anchors.bottom: parent .bottom
width: 60
}

Rectangle {
color: "yellow"
anchors.top: parent.top
anchors.bottom: parent.bottom
anchors.left: redrect.right
anchors.right: greenrect.left
}

Rectangle {
id: greenrect
color: "green"
806 VIII. Qt Quick

anchors.right: parent.right
anchors.top: parent.top
anchors.bottom: parent.bottom
width: 100

topMargin, bottomMargin,
leftMargin rightMargin, anchors,
. 55.7.

topMargin

2
C
5)
L.
CO

* > +->
i
CQ*
S
r+
2
fi)
C CQ
V
5'
I
bottomMargin

. 55.7. . 55.8.

( 55.8) ,
, . 55.8.
55.8 : ,
( color).
( right), .
leftMargin, topMargin, rightMargin bottomMargin
, 5 .
,
20 . ,
,
.
, Offset,
anchors 55.8,
:
verticalCenterOffset: 10
verticalCenter: parent .vert icalCenter

55.8.

import QtQuick 2.2


Item {
width: 360
height: 180
55. 807

Rectangle {
color: "red"
anchors {
right: parent.horizontalCenter
left: parent.left
top: parent.top
bottom: parent.bottom
leftMargin: 5
topMargin: 5
rightMargin: 5
bottomMargin: 5

Rectangle {
color: "green"
anchors {
left: parent.horizontalCenter
right: parent.right
top: parent.top
bottom: parent.bottom
leftMargin: 20
topMargin: 20
rightMargin: 20
bottomMargin: 20
}


,
Qt. .
:
Row, RowLayout , Qt
QHBoxLayout;
Column, ColumnLayout ,
Qt QVBoxLayout;
Grid, GridLayout , Qt
QGridLayout.
.
spacing layoutDirection.

.
, Layout,
QtQuick.Layouts , , Layout.
,
:
808 VIII. Qt Quick

Layout .minimumwidth ;
Layout .minimumHeight ;

Layout .maximumwidth ;

Layout .maximumHeight ;

Layout .preferredwidth ;

Layout .preferredHeight .

:
Layout . f iiiwidth ;
Layout . f illHeight .

Row
( 55.9) , . 55.9.

. 55.9. Row

55.9 (
centerin). , 10 .
Row ,
64x64 .

55.9. Row

import QtQuick 2.2


Item {
width: 360
height: 160

Row {
anchors. centerin: parent
spacing: 10
Rectangle {
width: 64; height: 64; color: "red"
}
Rectangle {
width: 64; height: 64; color: "blue"
}
55. 809

Rectangle {
width: 64; height: 64; color: "green"

}
}

RowLayout (
55.10).
,
, . 55.10.

. 55.10. RowLayout

55.10 QtQuick. Layouts .


RowLayout anchords. fill
(parent). (), 10 ( margins),
10 ( spacing).
fillHeight Rectangle
true .

fillwidth true. Rectangle
64x64 minimumWidth minimumHeight.

55.10. RowLayout

import QtQuick 2 2 .
.
import QtQuick Layouts 1 1 .
Item {
width: 320
height: 240

RowLayout {
anchors. fill: parent
anchors .margins : 10
spacing: 10
810 VIII. Qt Quick

Rectangle {
Layout.fillHeight: true
Layout.minimumWidth: 64;
Layout.minimumHeight: 64;
color: "red"
}
Rectangle {
Layout.fillwidth: true
Layout.minimumWidth: 64;
Layout.minimumHeight: 64;
color: "blue"

Rectangle {
Layout.fillHeight: true
Layout.minimumWidth: 64;
Layout.minimumHeight: 64;
color: "green"

, ,
55.9 Row Column.
: rows column,
.
( 55.11), . 55.11.

. 55.11.

55.1 1 55.9 ,
rows columns ,
2, .

55.11.

import QtQuick 2.2


Item {
width: 200
height: 200
55. 811

Grid {
rows: 2
columns: 2
anchors.centerln: parent
spacing: 10

Rectangle {
width: 64; height: 64; color: "red"
}
Rectangle {
width: 64; height: 64; color: "blue"

Rectangle {
width: 64; height: 64; color: "green"
}
Rectangle {
width: 64; height: 64; color: "black"

, Qt,

. QML ,
.
.
, QML
.
56

QML , ,
,
.

QML Qt.
.
, SVG. , ,
: "red", "green", "darkkhaki", "snow" . .
148 : www.neonway.com/colors.
: #rrggbb, HTML:
"#FFOOOO", "#OOFEOO", "#OOOOAF" . . ,
, . Qt Creator
(. 56.1).
, color,
Show Qt Quick Toolbar.
,
.
rgba ( )
. :
Rectangle {
color: Qt. rgba (0.3, 0.45, 0.21)
opacity: 0.5
}

(, . red)
Qt
Qt, 17
(. . 17.1).
opacity.
. , ,
56. 813

, .
0.5
.
1 7.

. 56.1. Qt Creator


QML : image Borderimage.

QML, JPG, PNG SVG.

Image
image , source.
, ,
URL, .
image (. 56.2) Qt Creator
. , image
, Show Qt Quick Toolbar.
.

:/ Desktop; vt. png 'I | ... |


OB
OO OB 0O
615x267
1
. 56.2. image Qt Creator
814 VIII. Qt Quick

,
/ ( scale) ( rotation).
.

transformOrigin. ,
, :
Image {

transformOrigin: Item.Top

( 56.1) ,
image (. 56.3).

. 56.3.

56.1 Rectangle,
image. "aqua" ,
( width height),
img. image.
0, 0 ( ). smooth true
, .
source "balalaika.png", ,
"qrc:". scale
:
, . -
56. 815

. rotation
30 , ,
. width height
,
, .

56.1.

import QtQuick 2.2


Rectangle {
color: "aqua"
width: img.width
height: img.height

Image {
id: img
x: 0
y: 0
smooth: true
source: "qrc:///balalaika.png"
scale: 0.75
rotation: -30.0

.
56.2 image, ,
image 56.1.
transform.
, . ,
. QML ,
, .
,
: Scale Rotation.
( origin. origin.).
Scale 0.75 :
( xScale yScale). Rotation angle
30 .

56.2.
import QtQuick 2.2
Image {
id: img
x: 0
y: 0
smooth: true
source: "qrc:///balalaika.png"
transform: [
816 VIII. Qt Quick

Scale {origin.x: width / 2


origin.: height / 2
xScale: 0.75
yScale: 0.75
b
Rotation {origin.x: width / 2
origin.: height / 2
angle: -30.0

Borderlmage
Borderlmage .
.
, .
Borderlmage ,
. ,
, . 56.4.
, left, right, top bottom.
,
( 56.3).
. . 56.5 ,
.

left right

. 56.4. . 56.5.

56. 817

56.3 source
. Borderimage
, ,
( width height). ,
left, top, right bottom.

56.3.

import QtQuick 2.2


Borderlmage {
source: "qrc:///button.png"
width: 100
height: 45
border {left: 30; top: 15; right: 30; bottom: 15}
}

QML .
gradient, Gradient.
( Gradient stop).
0 ( ) 1 ( ) .

. , ,
.
( 56.4) , ,
. 56.6.
Rectangle ( 56.4) gradient Gradient,
Gradientstop: 0,

0.7 1 ( position).
( color).
( rotation scale).

56.4.

import QtQuick 2.2


Rectangle {
width: 200
height: 200
gradient: Gradient {
Gradientstop {position: 0.0; color: "blue"}
Gradientstop {position: 0.7; color: "gold"}
Gradientstop {position: 1.0; color: "silver"}
}
rotation: 30;
scale: 1.5
818 VIII. Qt Quick

. 56.7.
Qt Creator

Qt Creator .
gradient,
Show Qt Quick Toolbar, , . 56.7.

.
,
. ,
, ,
, .
. :
import QtQuick 2.2
Rectangle {
width: 300
height: 300
Image {
x: 0;
y: 0
source: "qrc:///images/gradient.png"

font.
Text Helvetica ( family) 24 (
pixelSize) ( bold):
Text {

font {
family: "Helvetica"
pixelSize: 24
56. 819

bold: true
}


Qt Creator.
font,
Show Qt Quick Toolbar. , . 56.8,
.

. 56.8. Qt Creator


Canvas .
.
QpaintDevice, IV QPainter.
, QML , , ,
,
JavaScript. Canvas onPaint,
QWidget: rpaintEvent () .
JavaScript.
( 56.5) ,
. 56.9. 52.
56.5 400x400,
Canvas. anchors,fill
. QML , onPaint JavaScript.
drawFantasy ( ) .
ctx,
.
beginPath ( )
. translate ()
.
fAngle , moveTo ( )
, lineTo ( ) . -
820 VIII. Qt Quick

translate () rotate ()
f Angle. closePathO
.

. 56.9. Canvas

, ,
getContext ( ) . "2d" ,
, : X Y.
clearRect ( ) .
save ( )
, , ,
Canvas ,
.
strokeStyle .
linewidth ,
1.
drawFantasy ( )
stroke ( ) .
restore ( )
, save ( ) .

56.5.

import QtQuick 2.2


Item {
width: 400
height: 400
56. 821

Canvas {
anchors.fill: parent
onPaint: {
function drawFantasy()
{
ctx.beginPath()
ctx.translate(parent.width / 2, parent.height / 2)
var fAngle = 91 * 3.14156 / 180
for (var i = 0; i < 300; ++i) {
var n = i * 2
ctx.moveTo(0, 0)
ctx.lineTo(n, 0)
ctx.translate(n, 0)

ctx.rotate(fAngle)
}
ctx.closePath()
}
var ctx = getContext("2d");
ctx.clearRect(0, 0, parent.width, parent.height)
ctx.save();
ctx.strokeStyle = "black"
ctx.lineWidth = 1

drawFantasy();

ctx.stroke();
ctx.restore();


: image Borderimage, .
, ,
,
.
.
1

57

..., .

QML .
: .
.


QML ,
MouseArea . , ,
.
, ,
.
( 57.1), ,
(. 57.1).

Click Me!
(use left & right buttons)

. 57.1.

57.1 - ( Text),
. , ,

.
( MouseArea),
Rectangle. fill , -
57. 823

, .
, .
(onPressed onReleased),
.
, "on". ,
Qt, , ,
. onPressed onReleased
. ,
, . onPressed
mouse, , ,
.

, . accept edButtons
.

57.1.

import QtQuick 2.2


Rectangle {
width: 360
height: 200
color: "lightgreen"
Text {
anchors.centerln: parent
text: "<hl><center>Click Me!<br>
(use left or right mouse button) </centerx/hl>"
}

MouseArea {
anchors.fill: parent
acceptedButtons: Qt .LeftButton | Qt.RightButton
onPressed: {
if (mouse.button == Qt .RightButton) {
parent.color = "red"
}
else {
parent.color = "blue"

onReleased: parent.color = "lightgreen"


}
}

( 57.2)

(. 57.2).
57.2 mousearea,
, ( Rectangle)
, .
.
824 VIII. Qt Quick

f*

. 57.2.

Hover Me!

hoverEnabled true.
MouseArea .

57.2. hover

import QtQuick 2.2


Rectangle {
width: 200
height: 200
color: mousearea.containsMouse ? "red : "lightgreen"

Text {
anchors.centerln: parent
text: "<Hl>Hover Me!</Hl>"
}

MouseArea {
id: mousearea
anchors.fill: parent
hoverEnabled: true

onEntered
onExit. ,
, . . .
57.3.

57.3. hover,
import QtQuick 2.2
Rectangle {
width: 200
height: 200
color: "lightgreen"
Text {
text: "<Hl>Hover Me!</Hl>"
57. 825

anchors.centerln: parent
}
MouseArea {
id: mousearea
anchors.fill: parent
hoverEnabled: true
onEntered: parent.color = "red"
onExited: parent.color = "lightgreen"

57.3 , 57.2, hoverEnabled


true .
onEntered MouseArea ,
onExited - .

Qt . , QML
. QML ,
. QML
. , , ,
"on". , ,
, .
,
MouseArea onPressed, onReleased, onClicked . .
,
.
signal. :
signal <name>[ (<type> <value>, .. . ) ]

:
on<Name>: <expression>
.
( 57.4).
(. 57.3).

. 57.3.
826 VIII. Qt Quick

57.4, signal, .

: . ,
, "on", ,
Qt Creator -,
onMouseXChanged onMouseYChanged.
txt
.
. ,
onMousePositionChanged
. : mousex mouseY

. ,
, .

57.4.

import QtQuick 2.2


Rectangle {
width: 300
height: 150

signal mousePositionChanged(real x, real y)

onMousePositionChanged:
txt.text = <hl>X:" + x + Y:" + + "</hl>"

Text {
id: txt
text: "<hl>Move the Mouse</hl>"
anchors.centerln: parent
}
MouseArea {
anchors.fill: parent
hoverEnabled: true

onMouseXChanged: parent.mousePositionChanged(mouseX, mouseY)


onMouseYChanged: parent.mousePositionChanged(mousex, mouseY)

( 57.5) (. 57.4),
clicked.
.

. 57.4.

57. 827

.
. , 57.5,
Button.qml. Borderimage.
Text, , ,
-. clicked,
, onClicked
. ,
Borderimage 15
.
.
, onPressed onReleased.

57.5. . Button.qml

import QtQuick 2.2


Borderimage {
property alias text: txt.text
signal clicked;

source: "qrc:///button.png"
width: txt.width + 15
height: txt.height + 15
border {left: 15; top: 12; right: 15; bottom: 12}

Text {
id: txt
color: "white"
anchors.centerln: parent
}

MouseArea {
anchors.fill: parent
onClicked: parent.clicked();
onPressed: parent.source = "qrc:///buttonpressed.png"
onReleased: parent.source = "qrc:///button.png"

, 57.6,
.
text .
onClicked .

57.6.

import QtQuick 2.2


Item {
width: 150
height: 100
828 VIII. Qt Quick

Button {
anchors.centerln: parent
text: "Please, Click me!"
onClicked: {
text = "Clicked!"
}
}
}

,
. .

.
.

,
, .
, ,
.
. , , ,
, !
,
clicked ( 57.7).
57.5.
clicked .
onPressed onReleased.

57.7. . Button.qml

import QtQuick 2.2


Borderlmage {
property alias text: txt.text
property bool clicked;

source: "qrc:///button.png"
width: txt.width + 15
height: txt.height + 15
border {left: 15; top: 12; right: 15; bottom: 12}

Text {
id: txt
color: "white"
anchors.centerln: parent
}

MouseArea {
anchors.fill: parent
onPressed: {
parent.source = "qrc:///buttonpressed.png"
parent.clicked = false
}
57. 829

onReleased: {
parent.source = "qrc:///button.png"
parent.clicked = true

, 57.6 57.8,
, onClicked,
onClickedChanged, . . .

57.8.

import QtQuick 2.2


Item {
width: 150
height: 100
Button {
anchors.centerln: parent
text: "Please, Click me!"
onClickedChanged: {
text = "Clicked!"
}


: Textinput
TextEdit. , .
Textinput , TextEdit

, , Qt QLineEdit QTextEdit.
( 57.9) Textinput
(. 57.5).

. 57.5.

57.9 .
, , true (
focus). .
, Textinput ?
0, .
, width .
830 VIII. Qt Quick

57.9.

import QtQuick 2.2


Rectangle {
width: 200
height: 100
TextInput {
anchors.centerln: parent
color: "red"
text: "Text"
font.pixelSize: 32
focus: true


. .
Textinput, . ,
.
, , focus.
( 57.10)
.
(. 57.6).

_
TextEdit 1 TextEdit2
TextEditl TextEdit2
TextEditl TextEditZ
. 57.6.

57.10 . ,
focus, .

, . ,

, .

57.10.

import QtQuick 2.2


Item {
width: 200
height: 80
TextEdit {
anchors.left: parent.left
anchors.right: parent.horizontalCenter
57. 831

anchors.top: parent.top
anchors.bottom: parent.bottom
text: "TextEdit1\nTextEdit1\nTextEdit1"
font.pixelSize: 20
color: focus ? "red" : "black
focus: true

TextEdit {
anchors.left: parent.horizontalCenter
anchors.right: parent.right
anchors.top: parent.top
anchors.bottom: parent.bottom
text: "TextEdit2\nTextEdit2\nTextEdit2"
font.pixelSize: 20
color: focus ? "red" : "black"

,
, . . . ( 57.1 1)
: , (. 57.7).
- .
.

. 57.7.

57.1 1
KeyNavigation.tab.
Rectangle.
,
focus color .
( focus).
832 VIII. Qt Quick

KeyNavigation.tab, ,
,
, .

57.11.

import QtQuick 2.2


Rectangle {
width: 300
height: 300
color: focus ? "red" : "lightgreen"
KeyNavigation.tab: childrect

Rectangle {
id: childrect
width: 150
height: 150
anchors.centerln: parent
color: focus ? "red" : "lightgreen"
KeyNavigation.tab: parent
focus: true

Text {
anchors.centerIn: parent
text: "Press TAB"
}
}
}

,
, , KeyNavigation.right,
KeyNavigation.left, KeyNavigation.up KeyNavigation.down.



. ,
Keys.
( 57.12) ,
(. 57.8).

Move this text


(use the cursor-keys}

. 57.8.
57. 833

57.12 :
<< > (Keys.onLeftPressed),
< (Keys . onRightPressed), <>
(Keys . onDownPressed) <> (Keys.onUpPressed).
3 .
.

57.12.

import QtQuick 2.2


Rectangle {
width: 200
height: 100
Text {
x: 20;
y: 20;
text: "Move this text <br>(use the cursor-keys)"
horizontalAlignment: Text.AlignHCenter
Keys.onLeftPressed: x -= 3
Keys.onRightPressed: x += 3
Keys.onDownPressed: += 3
Keys.onUpPressed: -= 3
focus: true

57.13 , ,
onPressed,
(event.key) Qt
(. . 14.2).

57.13.

Keys.onPressed: {
if (event.key == Qt.Key_Left) {
x -= 3;
}
else if (event.key == Qt.Key_Right ) {
x += 3;
}
else if (event.key == Qt.Key_Down) {
+= 3;
}
else if (event.key == Qt.Key_Up) {
-= 3;

Keys . forwardTo
, .
834 VIII. Qt Quick

MouseArea.
,
.
"on".
Qt Creator,
.
Textinput TextEdit,
.
KeyNavigation Keys.
58

, ,
, .
.

22. ,
? , ,
, Qt, QML
, . . .
.

,
. ,
, .
,
.
, . ,
-, ,
. . , . ,
,
.
.
, QML , :
?
, QML,
,
QML: real, int, color, rect, point, size vector3d.


PropertyAnimation.

, .
( 58.1) , :
,
(. 58.1).
836 VIII. Qt Quick

. 58.1.

58.1 image
ProperyAnimation Rectangle. target
, . propeties
, .
from , to .
, 0
,
. ,
, duration ,
1,5 . , ,
, running true.
loop
Animaion.infinite, .

58.1.

import QtQuick 2.2


Rectangle {
color: "lightgreen"
width: 300
height: 300
Image {
id : img
x: 0
y: 0
source: "qrc: ///happyos.png"
}
PropertyAnimation {
target : img
properties: x,y"
from: 0
to: 300
img. height
58. 837

duration: 1500
running: true
loops: Animation.Infinite
easing.type: Easing.OutExpo

.
, ,
, . (. 58.1)

easing.type. Qt
, QML-, . 22.1
. ,
Qt Creator easing.type,
Show Qt Quick Toolbar,
, . 58.2.

Easing Bounc tI Subtype Outln


Duration 1450 m lTl Amplitude 1.950 (T)
Period 0.300 Overshoot 1.702

. 58.2.



.
.
. , ,
, , .
, PropertyAnimation.
:
NumberAnimation ;
ColorAnimation ;
RotationAnimation .


NumberAnimation ,
PropertyAnimation,
real int.
( 58.2)
(. 58.3).
838 VIII. Qt Quick

. 58.3. NumberAnimation

58.2 :
-
, ,
( color).
100 ( height). NumberAnimation
"on"

width. (from, to, duration, easing. type)
PropertyAnimation (. 58.1).

58.2. NumberAnimation

import QtQuick 2.2


Rectangle {
width: 300
height: 100
color: "lightgreen"

Rectangle {
x: 0
y: 0
height : 100
color: "red"
NumberAnimation on width {
from: 300
to: 0
duration: 2000
easing. type: Easing. InOutCubic


ColorAnimation
from to.
( 58.3)
(. 58.4).
58.3 from to ,
. . ,
, 1 ,5 (
58. 839

duration). true running


.

58.3. ColorAnimation

import QtQuick 2.2


Rectangle {
width: 200
height: 200
ColorAnimation on color {
from: Qt.rgba(l, 0.5, 0, 1)
to: Qt.rgba(0.5, 0, 1, 1)
duration: 1500
running: true
loops: Animation.Infinite

. 58.4. . 58.5.
ColorAnimation RotationAnimation


RotationAnimation .
direction, .
:
RotationAnimation.Clockwise ;
RotationAnimation.Counterclockwise ;
RotationAnimation.Shortest
, from, to.
.
( 58.4)
RotationAnimation (. 58.5).
58.4 RotationAnimation
image. 2
( ) 0 360 .
840 VIII. Qt Quick

58.4. RotationAnimation
import QtQuick 2.2
Rectangle {
width: 150
height: 150
Image {
source: " qrc:///happyos.png"
anchors.centerln: parent
smooth: true

RotationAnimation on rotation {
from: 0
to: 360
duration: 2000
loops: Animation.Infinite
easing.type: Easing.InOutBack


, ,
- . ,
,
, . , ,
, .
Behavior.
( 58.5)
(. 58.6).

ft

Move the mouse!

. 58.6.
58. 841

58.5 Behavior,
image.
NumberAnimation
, 1 . ,
.
image
MouseArea onMouseXChanged onMouseYChanged.

58.5.

import QtQuick 2.2


Rectangle {
id: rect
width: 360
height: 360
Image {
id: img
source: " qrc:///happyos.png"
x: 10
y: 10
smooth: true
Text {
anchors.verticalCenter: img.verticalCenter
anchors.top: img.bottom
text: "Move the mouse!"

Behavior on x {
NumberAnimation {
duration: 1000
easing.type: Easing.OutBounce
}
}
Behavior on {
NumberAnimation {
duration: 1000
easing.type: Easing.OutBounce

}
MouseArea {
anchors.fill: rect
hoverEnabled: true

onMouseXChanged: img.x = mouseX


onMouseYChanged: img. = mouseY
842 VIII. Qt Quick


, .
, ?
.
.
.
SequentialAnimation.
. ,
.
ParallelAnimation ,
. ,
.
.
, , :
Rectangle {

PropertyAnimation on {to: 50; duration: 1000}


PropertyAnimation on {to: 50; duration: 1000}

,
, , ( 58.6).
(. 58.7)
.
58.6 :
( scale) 1 3 ( opacity)

. 58.7.
58. 843

( 1 0).
, ,
image, target
img. 2
( duration). ,
, running true,
, loop Animation.
Infinite.

58.6.

import QtQuick 2.2


Rectangle {
width: 400
height: 400
Image {
id: img )
source: " qrc:///happyos.png"
smooth: true
anchors.centerln: parent
}

ParallelAnimation {
NumberAnimation {
target: img Click me!
properties: "scale"
from: 0.1;
to: 3.0;
duration: 2000
easing.type: Easing.InOutCubic
}
NumberAnimation {
target: img
properties: "opacity"
from: 1.0
to: 0;
duration: 2000
}
running: true
loops: Animation.Infinite
I . 58.8.

}

, , ,
. , .
, , ,
, . ,
, ( 58.7). . 58.8
, , . .
.
844 VIII. Qt Quick

58.7 , .
onClicked MouseArea.
( running), anim.
( SequentialAnimation).
NumberAnimation
20 ( from) 300 ( to) ( ).
1 ( duration).
,
RotationAnimation,
from to 0 360 .
direction, , . .
( RotationAnimation.Clockwise) .
1 .
,
. .
: .
duration ,
500, . . 0,5 .
.
NumberAnimation,
300 20 ( from to).
0,5 ( duration).

58.7.

import QtQuick 2.2


Rectangle {
width: 130
height: 450
Image {
id: img
source: " qrc:///happyos.png"
smooth: true
Text {
anchors.horizontalCenter: img.horizontalCenter
anchors.top: img.bottom
text: "Click me!"
}
MouseArea {
anchors.fill: img
onClicked: anim.running = true
}
SequentialAnimation {
id: anim
NumberAnimation {
target: img
from: 20
to: 300
58. 845

properties: ""
easing.type: Easing.OutBounce
duration: 1000
}
RotationAnimation {
target: img
from: 0
to: 360
properties: "rotation"
direction: RotationAnimaion.Clockwise
duration: 1000
}
PauseAnimation {
duration: 500
}
NumberAnimation {
target: img
from: 300
to: 20
properties: "y"
easing.type: Easing.OutBack
duration: 1000
}
}


,
. , , ,
,
.
, . ,
, 25-30 , -
. :
? , ,
- .
, -
.

QML state.

, . .
. ,
.
JavaScript,
.
846 VIII. Qt Quick

, ( 58.8),
.
. . 58.9 ,
. 58.10 , .


State2: Click Mel

. 58.10. ()

Qt Creator main.qml ( 58.8)


( Rectangle), ( Text).
id . ,
:
rect, txt.
.
QML.
states. . ,
,
state. ,
state2. , ,
.


, ,
,
state , , "statel".

? ,
.
PropertyChanges. ,
, target.
,
. ,
58. 847

.
color, width height Rectangle,
Text text.
,
.
Rectangle. onClicked
, .
state "Statel", ,,state2", .
, 58.8
. , . .
.

,
UML (Unified Modeling Language,
), Rational Rose.
.

58.8. . main.qml

import QtQuick 2.2


Rectangle {
id: rect
width: 360
height: 360
state: ,,State2"
Text {
id: txt
anchors.centerln: parent
}
states: [
State {
name: "Statel"
PropertyChanges {
target: rect
color: "lightgreen"
width: 150
height: 60
}
PropertyChanges {
target: txt
text: "State2: Click Me!"
}
},
State {
name: "State2"
PropertyChanges {
target: rect
color: "yellow"
848 VIII. Qt Quick

width: 200
height: 120
}
PropertyChanges {
target: txt
text: "Statel: Click Me!"

MouseArea {
anchors.fill: parent
onClicked:
parent.state = (parent.state == "Statel") ? "State2" : "Statel"

, ,
.
,
, . . ,
.
, ,
, .
, QML: ,
, , , .
,
. ,
, , , . .
.
.
. ( 58.9)
, . 58.1 1 58.12, .
58.8, 58.9
.
transitions .
Transition .
.
from to,
. .
statel state2,
, . . State2 statel.
PropertyAnimation,
.

-
58. 849

. 58.11. statel . 58.12. state2


duration. 1 .
easing. type .

58.9.

import QtQuick 2.2


Item {
width: 300
height: 300
Rectangle {
id: rect
width: 100
height: 100
color: "magenta"
state: "Statel"
Text {
anchors. centerln: parent
text: "Click me!"
}
MouseArea {
.
anchors fill : rect
onClicked:
rect.state = (rect. state == "Statel") ? "State2" : "Statel"
}
states: [
State {
name: "Statel"
PropertyChanges (target: rect; x: 0; y: 0}
b
850 VIII. Qt Quick

State {
name: "State2"
PropertyChanges {target: rect; x: 200; y: 200}
}
]
transitions: [
Transition {
from: "Statel"; to: "State2"
PropertyAnimation {
target: rect;
properties: "x,y";
easing.type: Easing.InCirc
duration: 1000
}

Transition {
from: "State2; to: "Statel"
PropertyAnimation {
target: rect
properties: "x,y";
easing.type: Easing.InBounce
duration: 1000
}
}

(. 58.9)
(Easing.InCirc Easing.InBounce).
, PropertyAnimation ,
.
transitions 58.9 , 58.10,
.

58.10.

transitions:
Transition {
from: "*"; to: "*"
PropertyAnimation {
target: rect;
properties: "x,y";
easing.type: Easing.InCirc
duration: 1000

"*" (. . 58.10).
, -
58. 851

. ,
, 58.9.
Easing.inCirc.

. , QML, ,
, .
,
, C++.
QML .
PropertyAnimation.
.
. Qt Creator

.
-.
.
.
.
.
.

.
.
59


, .

QML, (Interview), Qt
(. 12), .
,
, .

, ,
,
.
, .
, QML, ListModel
xmlListModel. , C++
(. 60), , ,
QML.
QML.


ListModel
:
ListModel {
ListElement{...}
ListElement{...}

ListElement .
ListElement
. - ( 59.1)
artist (), album (), year () cover ().
59. / 853

59.1. . CDs.qml

import QtQuick 2.2


ListModel {
ListElement {
artist: "Amaranthe"
album: "Amaranthe"
year: 2011
cover: "qrc:///covers/Amaranthe.png"
}
ListElement {
artist: "Dark Princess"
album: "Without You"
year: 2005
cover: "qrc:///covers/WithoutYou.png"
}
ListElement {
artist: "Within Temptation"
album: "The Unforgiving"
year: 2011
cover: "qrc:///covers/TheUnforgiving.png"

59.1 .
, -
(CD), cover
CD.
, 59.1 ,
ListModel .
, ,
ListModel append(), insert(), remove() move().
CDs.qml.
, ,
, id .
CDs.qml 59.1 .

XML-
, XML-.
Web-.
. xmlListModel
XML-. XmlListModel
xPath (. 40) .
, XML-
, XML- ( 59.2).
.
854 VIII. Qt Quick

59.2. XML-. CDs.xml

<?xml version = "1.0"?>


<CDs>
<CD>
<artist>Amaranthe</artist>
<album>Amaranthe</album>
<year>2011</year>
<cover>qrc:///covers/Amaranthe.png</cover>
</CD>
<CD>
<artist>Dark Princess</artist>
<album>Without You</album>
<year>2005</year>
<cover>qrc:///covers/WithoutYou.png</cover>
</CD>
<CD>
<artist>Within Temptation</artist>
<album>The Unforgiving</album>
<year>2011</year>
<cover>qrc:///covers/TheUnforgiving.png</cover>
</CD>

</CDs>

59.2 XML-.
. 59.1.
CDs.xml .
, CDs.xml.
xmlListModel ( 59.3).

59.3. XML-. CDs.qml

import QtQuick 2.2


import QtQuick.XmlListModel 2.0
XmlListModel {
source: "qrc:///CDs.xml"
query: "/CDs/CD"
XmlRole {name: "artist"; query: "artist/string()"}
XmlRole {name: "album"; query: "album/string()"}
XmlRole {name: "year"; query: "year/string()"}
XmlRole {name: "cover"; query: "cover/string()"}

59.3 . XmlListModel
source, , XML-
, . .
XML- CDs.xml,
59.2.
59. / 855

, XPath.
.
, XML-.
, , , xmlRole.
. name ,
, query . query
. .
"/Cds/CD", query
XmlListModel.


QML :
Listview
,
;
Gridview ,
;
Pathview .
, Flickabie.

Flickabie
Flickabie ,
.
Qt QScrollArea (. 5)
, .
.
.
59.4.
Flickabie ,
Flickabie (. 59.1).

. 59.1.

Flickabie

59.4 Flickabie 150 150.



contentwidth contentHeight ( image).
856 VIII. Qt Quick

image, image
Alina.png, .

59.4.

import QtQuick 2.2


Flickable {
width: 150
height: 150
contentwidth: image.width
contentHeight: image.height

Image {
id: image
source: "qrc:///Alina.png"

ListView

Listview.
( 59.2). CDs

59.1 59.3
(. 59.2).
.
Dark Princess
59.5 7 'f
Without You
200s
Rectangle, ( color)
200x360.
*

Within Temptation
The Unforgiving

Evanescence
[Fallen
12003

Tristania
% , Rubicon
. 59.2. 2010
Listview

.
Component
delegate, id. ,
. item ,
. Row
, ( image),
,
Column. image , -
59. / 857

cover. Text
artist, album year.
Listview.
,
( anchors).
. ,
, focus .
Listview .
header footer, highlight

. footer
( Gradient) "CDs" ( Text).
( footer) ,
. ( highlight)
( color).
: .
model delegate.
, model,
delegate.

59.5. Listview. main.qml

import QtQuick 2.2


Rectangle {
id: mainrect
color: "gray"
width: 200
height: 360
Component {
id: delegate
Item {
width: mainrect.width
height: 70
Row {
anchors.verticalCenter: parent.verticalCenter
Image {
width: 64
height: 64
source: cover
smooth: true
}
Column {
Text {color: "white"; text: artist; font.pointSize: 12}
Text {color: "lightblue"; text: album; font.pointSize: 10}
Text {color: "yellow"; text: year; font.pointSize: 8}
858 VIII. Qt Quick

ListView {
anchors.fill: parent
focus: true
header: Rectangle {
width: parent.width
height: 30
gradient: Gradient {
GradientStop {position: 0; color: "gray"}
GradientStop (position: 0.7; color: "black"}
}
Text{
anchors.centerln: parent;
color: "gray";
text: "CDs";
font.bold: true;
font.pointSize: 20

footer: Rectangle {
width: parent.width
height: 30
gradient: Gradient {
GradientStop {position: 0; color: "gray"}
GradientStop {position: 0.7; color: "black"}
}
}
highlight: Rectangle {
width: parent.width
color: "blue"
}
model: CDs{}
delegate: delegate

GridView
GridView
(. 59.3),
.
GridView ( 59.6)
Listview, 59.5.

59.6. GridView. main.qml

import QtQuick 2.2


Rectangle {
id: mainrect
color: "gray"
59. / 859

width: 380
height: 420
Component {
id: delegate
Item {
width: 120
height: 120
Column {
anchors.centerin, parent
Image {
anchors.horizontalCenter: parent.horizontalCenter
width: 64
height: 64
source: cover
smooth: true
}
Text {color: "white"; text: artist; font.pointSize: 12}
Text {color: "lightblue"; text: album; font.pointSize: 10}
Text {color: "yellow"; text: year; font.pointSize: 8}
}
}
}
GridView {
cellHeight: 120
cellWidth: 120
focus: true
header: Rectangle {
width: parent.width
height: 30
gradient: Gradient {
GradientStop {position: 0; color: "gray"}
GradientStop {position: 0.7; color: "black"}

Text{
anchors.centerln: parent;
color: "gray";
text: "CDs";
font.bold: true;
font.pointSize: 20
}
}
footer: Rectangle {
width: parent.width
height: 30
gradient: Gradient {
GradientStop {position: 0; color: "gray"}
GradientStop {position: 0.7; color: "black"}
}
860 VIII. Qt Quick

highlight: Rectangle {
width: parent.width
color: "darkblue"
}
anchors.fill: parent
model: CDs{}
delegate: delegate

. 59.3. Gridview

59.6 59.5 ,
Gridview Listview,
Column.

PathView
PathView . ,
,
.
CD ( 59.7). . 59.4
,
.
59. / 861

. 59.4. Pathview

59.7 59.5 59.6.


Path. .
0 500
80. , , Path startY 0,
. Path
Pathview path.
pathitemCount , .

59.7. Pathview. main.qml

import QtQuick 2.2


Rectangle {
color: "gray"
width: 450
height: 170
Component {
id: delegate
Item {
width: item.width
height: item.height
Column {
id: item
Image {
width: 90
height: 90
source: cover
smooth: true
}
Text {color: "white"; text: artist; font.pointSize: 12}
Text {color: "lightblue"; text: album; font.pointSize: 10}
Text {color: "yellow"; text: year; font.pointSize: 8}
}
}
}
Path {
id: itemsPath
862 VIII. Qt Quick

startX:
startY: 80
PathLine {x: 500; y: 80}
}
PathView {
id: itemsView
anchors.fill: parent
model: CDs {}
delegate: delegate
path: itemsPath
pathltemCount: 4


Path, -,
. 59.5. 59.7 Path
Path 59.8.

. 59.5. - PathView

59.8 Path PathQuad, .


:
, . ,
, PathAttribute
. 3D.

59.8. -. main.qml

Path {
id: itemsPath
startX: 150
startY: 150
59. / 863

PathAttribute {name: "iconScale"; value: 1.0}


PathAttribute {name: "iconOpacity"; value: 1.0}
PathQuad {x: 150; y: 25; controlX: 460; controlY: 75}
PathAttribute {name: "iconScale"; value: 0.3}
PathAttribute {name: "iconOpacity"; value: 0.3}
PathQuad {x: 150; y: 150; controlX: -80; controlY: 75}
}

QML /
: ListModel xmlModel. ,
, XML-,
.
: Listview, Gridview Pathview.
,
, .
,
.
60

Qt Quick C++

,
.

, , :
QML?
Qt Quick Qt/C++
?
Qt/C++ ?
QML ?
, .
, ? .

QML C++
QQuickwidget QML
QML-. QWidget, . . ,
, ,
Qt/C++. , ,
.
quickwidgets, .
( 60.1) ,
, QML- -
(. 60.1).

. 60.1.
QQuickwidget
60. Qt Quick C++ 865

:
QT += quick qml widgets quickwidgets

60.1. MyWidget.cpp. QDeclarativeView

MyWidget::MyWidget(QWidget* pwgt/*=0*/) : QWidget(pwgt)


{

QQuickWidget* pv = new QQuickWidget(QUrl("qrc:///main.qml"));

QVBoxLayout* pvbx = new QVBoxLayout;


pvbx->addWidget (pv);
setLayout(pvbx);

MyWidget ( 60.1) QQuickWidget


main.qml ( 60.2),
QML.
MyWidget QVBoxLayout.

60.2. main.qml

import QtQuick 2.2


Rectangle {
color: "lightgreen"
width: 100
height: 100
Text {
anchors.centerIn: parent
text:"Hello QML"

60.2 QML-,
( Text). QML-,
Rectangle - .

C++ QML
QML.
,
C++.
: QML, C++.
QML C++.
C++.
Qt. ,
, Qt Qt3D,
866 VIII. Qt Quick

QtMobility, QtwebKit, Qt,


import. , QtwebKit:
import QtwebKit 1.0

,
C++ Qt, QML,
.
QQmiContext.
, QQuickwidget
rootContext ( ) , .
, ,
QObject.
setContextProperty ( ) . . ,
QML, .
, QObject QML,
, Q_INVOKABLE, ,
QML-.
QQuickwidget QQmlEngine,
QML- QML-.
engine ().
Qt QML,
60.1 , Qt-
QML ( 60.3 60.4). QML- 60.2
. ,
QML, MyWidget
Its my message (. 60.2).

} Hello from QML

Iteml9
Item20
Item21
Item22
Item23
Item24 It's my text!
Item25
Item26
Item27
Item28 It's my message
Item29
1 4
?

1
OK

. 60.2. Qt- QML

60.3 QQuickwidget
, 60.1. , ,
. , rootContext ( )
QQuickwidget. QStringList for
60. Qt Quick C++ 867

. setstringList ( )
QStringListModel.
setContextProperty ( ) .
: QStringListModel, QString, QColor QWidget,
. ,
QML.
QML, "".
60.3 siotDisplayDiaiogO,
QML-.

60.3. MyWidget.cpp. Qt

MyWidget::MyWidget(QWidget* pwgt/*=0*/) : QWidget(pwgt)


{
QQuickWidget* pv = new QQuickWidget;
pv->setSource(QUrl("qrc:///main.qml"));

QVBoxLayout* pvbx = new QVBoxLayout;


pvbx->addwidget (pv);
setLayout(pvbx);

QQmlContext* peon = pv->rootContext();


QStringList 1st;
for (int i = 0; i < 100; ++i) {
1st "Item" + QString::number(i);
}
QStringListModel* pmodel = new QStringListModel(this);
pmodel->setStringList(1st);

pcon->setContextProperty("myModel", pmodel);
pcon->setContextProperty("myText", "It's my text!");
pcon->setContextProperty("myColor", QColor(Qt::yellow));
pcon->setContextProperty("myWidget", this);

void MyWidget::slotDisplayDialog()
{
QMessageBox::information(0, "Message", "It's my message");
}

60.4 4 .
( myColor) Rectangle ( color).
( myText) Text. (
myModel) Listview. , ,
MouseArea. onPressed ( myWidget)
setwindowTitle () "Hello from QML".
MyWidget siotDisplayDiaiogO,
.
868 VIII. Qt Quick

60.4. MyWidget.cpp. Qt
import QtQuick 2.2
Rectangle {
color: myColor
width: 200
height: 200
Text {
anchors.centerln: parent
text: myText
}
ListView {
anchors.fill:parent
model: myModel
delegate: Text {text: model.display}
}
MouseArea {
anchors.fill: parent
onPressed: {
myWidget.setWindowTitle("Hello from QML");
myWidget.slotDisplayDialog();
}


QQuickimageProvider

. QML

.
( 60.5-60.10)
QQuickimageProvider
(. 60.3).

QML,
C++.

. 60.3.
QQuickimageProvider QML
60. Qt Quick C++ 869

, 60.5,
QQmlApplicationEngine. QML-
ApplicationWindow. addlmageProvider()
ImageProvider, QQuicklmageProvider
. "brightness",
. load()
QML- .

60.5. main.cpp

#include <QtQml>
tinclude <QApplication>
tinclude <QQmlApplicationEngine>
tinclude "ImageProvider.h"

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


{
QApplication app(argc, argv);

QQmlApplicationEngine engine;

engine.addlmageProvider(QLatinlString("brightness"), new ImageProvider);

engine.load(QUrl(QStringLiteral("qrc:///main.qml")));

return app.exec();
)

ImageProvider QQuicklmageProvider ( 60.6).


brightness() / .
requestimageO
QML.

60.6. ImageProvider.h

#pragma once

#include <QObject>
#include <QImage>
#include <QQuickImageProvider>

// =================================================
class ImageProvider : public QQuicklmageProvider {
private:
Qlmage brightness(const Qlmages imgOrig, int n);

public:
ImageProvider();

Qlmage requestlmage(const QStrings, QSize*, const QSizeS);


870 VIII. Qt Quick

( 60.7) QQuickimageProvider
image. ,
Qimage.

QPixmap,
QQuickimageProvider Pixmap
requestedPixmap ().

60.7. ImageProvider.cpp.

ImageProvider::ImageProvider()
: QQuickimageProvider(QQuickimageProvider::Image)
{
}

/ , 60.8,
, . Qimage 19.

60.8. ImageProvider.cpp. /

Qimage ImageProvider::brightness(const Qlmages imgOrig, int n)


{
Qimage imgTemp = imgOrig;
qint32 nHeight = imgTemp.height();
qint32 nWidth = imgTemp.width();

for (qint32 = 0; < nHeight; ++y) {


QRgb* tempLine = reinterpret_cast<QRgb*>(imgTemp.scanLine(y));

for (qint32 x = 0; x < nWidth; ++x) {


int r = qRed(*tempLine) + n;
int g = qGreen(*tempLine) + n;
int b = qBlue(*tempLine) + n;
int a = qAlpha(*tempLine);

*tempLine++ = qRgba(r > 255 ? 255 < 0? 0 r


g > 255 ? 255 g < 0 ? 0 g
b > 255 ? 255 <0?0 b
a

return imgTemp;
)

requestimage () QML C++ ( 60.9).


. -
60. Qt Quick C++ 871

, :
. QML ; .
( ps) .
, , QML
.
,- QString::slit strid
int (

nBrightness) . brighness()
Qimage,
. brightness ( )
nBrightness. Qimage, img.
, ps , QSize, ,
.
.

60.9. ImageProvider.cpp.

Qimage ImageProvider::requestlmage(const QStrings strid, QSize* ps, const QSizes


/*requestedSize*/)
{
QStringList 1st = strid.split
bool bOk = false;
int nBrightness = 1st.last().tolnt(&bOk);
Qimage img = brightness(Qimage + 1st.first())i , nBrightness)

if (ps) {
*ps = img.size();
}

return img;
)

60.10 QML
.
( controls) width height.
: image, slider, Text. image
. , ,
ImageProvider,
source. image
brightness .
Alina.png, , ;
.
sid. , ,
width. 75 %,
value. 0
1, , 100, stepSize
0.01. brightnessvalue,
.
872 VIII. Qt Quick

image ,
Text .

60.10. main.qml. imageProvider

import QtQuick 2.2


import QtQuick.Controls 1.2

ApplicationWindow {
title: qsTr("Image Brightness")
width: controls.width
height: controls.height
visible: true

Column {
id: controls
Image {
id: img
source: "image://brightness/Alina.png;" + sld.brightnessValue
}
Slider {
id: sld
width: img.width
value: 0.75
stepSize: 0.01
property int brightnessValue: (value * 255 - 127)
}
Text {
width: img.width
text: "<hl>Brightness:" + sld.brightnessValue + "</hl>"


Q PROPERTY , Q INVOKABLE. ( 60.11-60.18)
, , ,
.
(. 60.4).
, 60.11,
qmlRegisterType<T> ( ) Calculation.

. 60.4. Q PROPERTY Q INVOKABLE


60. Qt Quick C++ 873

,
QML-. ,
. , , .

60.11. main.cpp

# include <QtQml>
# include <QApplication>
# include <QQmlApplicationEngine>
#include "Calculation. h"

int main(int argc, char** argv)


{
QApplication app(argc, argv);

qmlRegisterType<Calculation> ("com. myinc. Calculation", 1, 0, "Calculation");

QQmlApplicationEngine engine;
engine . load (QUrl (QStringLiteral ("qrc: ///main.qml") ) ) ;

return app . exec ( ) ;


}

Calculation ( 60.12) : input output.


, QObject.
input , Q_PROPERTY
: WRITE, : READ : NOTIFY.
result
,
, : READ
.
factorial ()
Q_INVOKABLE.
inputvalue ( ) , resultvalue ( ) , setlnputvalue ( )

inputValueChanged ( ) , resultValueChanged ( )

.

60.12. Calculation.h

#pragma once

#include <QObject>

class Calculation : public QObject {


QJDBJECT
private :
Q_PROPERTY (qulonglong input WRITE setlnputvalue
READ inputvalue
NOTIFY inputValueChanged
)
874 VIII. Qt Quick

Q_PROPERTY(qulonglong result READ resultValue


NOTIFY resultValueChanged
)

qulonglong input;
qulonglong result;

public:
Calculation(QObject* pobj = 0);

Q_INVOKABLE qulonglong factorial(const qulonglongs n);

qulonglong inputValue ( ) const;


void setlnputValue(const qulonglongs);
qulonglong resultValue ( ) const;

signals:
void inputValueChanged (qulonglong);
void resultValueChanged(qulonglong);
};

( 60.13) input result


.

60.13. Calculation.cpp.

Calculation: Calculation(QObject* pobj) : QObject(pobj)


, input(0)
, result(1)
{
)

factorial ( 60.14) .

60.14. Calculation.cpp.
qulonglong Calculation::factorial(const qulonglongs n)
{
return n ? (n * factorial(n -1)) : 1;
}

inputValue( ) ( 60. 1 5) input


.

60.15. Calculation.cpp. inputValue()

qulonglong Calculation::inputValue() const


{
return input;
60. Qt Quick C++ 875

resultvalue ( ) ( 60.16) result


.

60.16. Calculation.cpp. resultvalue()

qulonglong Calculation: : resultvalue ( ) const


{
return result;
}

set input value () ( 60.17) input


.
factorial ( )
. ,
inputValueChanged ( ) resultValueChanged ( ) .

60.17. Calculation.cpp. setinputvalue()

void Calculation: : set InputValue (const qulonglong& n)


{
input = n;
result = factorial (input ) ;

emit inputValueChanged ( input ) ;


emit resultValueChanged ( result ) ;
}

QML-, 60.18, com.myinc.


Calculation Calculation calc.
ColumnLayout -
RowLayout. factorial (),
Calculation Q_INVOKABLE. Text
(. text) .
value sbx,
Calculation
calc.
RowLayout
.
onValueChanged input Calculation
. 60.17,
result Calculation,
Text (. text).

60.18. main.qml

import QtQuick 2.2


import QtQuick. Controls 1.2
import QtQuick . Layouts 1.1
import com.myinc. Calculation 1.0
876 VIII. Qt Quick

ApplicationWindow {
title: "Factorial Calculation"
width: 250
height: 80
visible: true

Calculation {
id: calc
}

ColumnLayout {
anchors.fill: parent
RowLayout { // 1. call of an invokable method
SpinBox {
id: sbx
value: 0
}
Text {
text: "Result:" + calc.factorial(sbx.value)
}
}
RowLayout { // 2. using of the properties
SpinBox {
value: 0
onValueChanged: calc.input = value

Text {
text: "Result:" + calc.result
}

,
, . . , 60.17.
,
result ( 60.19).

60.19.

ApplicationWindow {
title: "Factorial Calculation"
width: 250
height: 40
visible: true

Calculation {
input: sbx.value
onResultValueChanged: txt.text = "Result:" + result
}
60. Qt Quick C++ 877

RowLayout {
SpinBox {
id: sbx
value: 0
}
Text {
id: txt
}
}
}

60.19 input Calculation value


SpinBox. onResultValueChanged

txt ( text).

Qt Quick Qt
C++. QQuickwidget, QML-
, QWidget, Qt-
.
QML , Qt
C++, QQmlContext.
setCont ext Propet ( ) , C++
QML. qmlRegisterType<T> ( )
, ,
Q INVOKABLE, QML.
QQuickimageProvider C++
, QML.

, , .
: ,
, , , ,
. , , ,
Max.Schlee@neonway.com,
www.maxschlee.com,
-
mail@bhv.ru.

www.facebook.com/mschlee
www.vkontakte.ru/max.schlee
www.odnoklassniki.ru/max.schlee
www.my.mail.ru ( )
. www.professionali.ru/~554418

, , , ,
Qt. ,
, , , Qt.
. , ,
,
, ,
.
, , ,
, ,
!
1. ASCII
2.
3.
4.
1

ASCII
ASCII (American Standard Code for Information Interchange,
)
, ,
. 128 (
7 ) . 1 . 1 ( )
. 1.2 (- ).
128 , ,
, Qt
- Unicode.

1.1.
DEC HEX

00 00 00 NUL

01 01 01 SOH

02 02 02 STX
03 03 03
04 04 04 EOT
05 05 05 ENQ

06 06

07 07 07 BEL

10 08 08 BS

11 09 09 TAB

12 10 0 LF

13 11 VT

14 12 FF

15 13 0D CR

16 14 0 SO

17 15 0F SI

20 16 10 DLE
882 1

1.1 ()

DEC HEX

21 17 11 DC1 1

22 18 12 DC2 2

23 19 13 DC3 3

24 20 14 DC4 4

25 21 15 NAK

26 22 16 SYN

27 23 17 ETB
30 24 18 CAN

31 25 19 EM
32 26 1 SUB
33 27 IB ESC

34 28 1C FS
35 29 ID GS
36 30 IE RS
37 31 IF US

1.2.

DEC HEX DEC HEX

40 32 20 () 60 48 30 0
41 33 21 1 61 49 31 1
42 34 22 " 62 50 32 2
43 35 23 # 63 51 33 3
44 36 24 $ 64 52 34 4
45 37 25 % 65 53 35 5
46 38 26 & 66 54 36 6
47 39 27 V
67 55 37 7
50 40 28 ( 70 56 38 8
51 41 29 ) 71 57 39 9
52 42 2
72 58
53 43 2 + 73 59 ;

54 44 2 74 60 <
55 45 2D - 75 61 3D =
56 46 2 76 62 >
57 47 2F / 77 63 3F ?
ASCII 883

1.2 ()

DEC HEX DEC HEX

80 64 40 0 120 96 60

81 65 41 121 97 61

82 66 42 122 98 62
83 67 43 123 99 63

84 68 44 D 124 100 64 d
85 69 45 125 101 65

86 70 46 F 126 102 66 f

87 71 47 G 127 103 67 g

90 72 48 130 104 68 h

91 73 49 I 131 105 69 i

92 74 4 J 132 106 6 j

93 75 4 133 107 6
94 76 4 L 134 108 6 1

95 77 4D 135 109 6D m

96 78 4 N 136 110 6 n

97 79 4F 137 111 6F

100 80 50 140 112 70 p

101 81 51 Q 141 113 71 q

102 82 52 R 142 114 72 r

103 83 53 S 143 115 73 s

104 84 54 144 116 74 t

105 85 55 145 117 75 u

106 86 56 V 146 118 76 V

107 87 57 W 147 119 77 w

110 88 58 X 150 120 78 X

111 89 59 Y 151 121 79 Y


112 90 5 Z 152 122 7 z

113 91 5 [ 153 123 7 {

114 92 5 \ 154 124 7 1


115 93 5D ] 155 125 7D }

116 94 5 * 156 126 7 ~


117 95 5F _ 157 127 7F DEL
2

. 2.1 .

2.1.

2 3 5 7 11 13 17 19 23 29 31 37 41 43

47 53 59 61 71 73 79 83 89 97 101 103 107 109

113 127 131 137 139 149 151 157 163 167 173 179 181 191

193 197 199 211 223 227 229 233 239 241 251 257 263 269

271 277 281 283 293 307 311 313 317 331 337 347 349 353

359 367 373 379 383 389 397 401 409 419 421 431 433 439

443 449 457 461 463 467 479 487 491 499 503 509 521 523

541 547 557 563 569 571 577 587 593 599 601 607 613 617

619 631 641 643 647 653 659 661 673 677 683 691 701 709

719 727 733 739 743 751 757 761 769 773 787 797 809 811

821 823 827 829 839 853 857 859 863 877 881 883 887 907

911 919 929 937 941 947 953 967 971 977 983 991 997 1009

1013 1019 1021 1031 1033 1039 1049 1051 1061 1063 1069 1087 1091 1093
1097 1103 1109 1117 1123 1129 1151 1153 1163 1171 1181 1187 1193 1201

1213 1217 1223 1229 1231 1237 1249 1259 1277 1279 1283 1289 1291 1297

1301 1303 1307 1319 1321 1327 1361 1367 1373 1381 1399 1409 1423 1427
1429 1433 1439 1447 1451 1453 1459 1471 1481 1483 1487 1489 1493 1499

1511 1523 1531 1543 1549 1553 1559 1567 1571 1579 1583 1597 1601 1607
1609 1613 1619 1621 1627 1637 1657 1663 1667 1669 1693 1697 1699 1709

1721 1723 1733 1741 1747 1753 1759 1777 1783 1787 1789 1801 1811 1823
1831 1847 1861 1867 1871 1873 1877 1879 1889 1901 1907 1913 1931 1933

1949 1951 1973 1979 1987 1993 1997 1999 2003 2011 2017 2027 2029 2039

2053 2063 2069 2081 2083 2087 2089 2099 2111 2113 2129 2131 2137 2141
2143 2153 2161 2179 2203 2207 2213 2221 2237 2239 2243 2251 2267 2269
885

2.1 ()

2273 2281 2287 2293 2297 2309 2311 2333 2339 2341 2347 2351 2357 2371
2377 2381 2383 2389 2393 2399 2411 2417 2423 2437 2441 2447 2459 2467
2473 2477 2503 2521 2531 2539 2543 2549 2551 2557 2579 2591 2593 2609
2617 2621 2633 2647 2657 2659 2663 2671 2677 2683 2687 2689 2693 2699
2707 2711 2713 2719 2729 2731 2741 2749 2753 2767 2777 2789 2791 2797
2801 2803 2819 2833 2837 2843 2851 2857 2861 2879 2887 2897 2903 2909
2917 2927 2939 2953 2957 2963 2969 2971 2999 3001 3011 3019 3023 3037

3041 3049 3061 3067 3079 3083 3089 3109 3119 3121 3137 3163 3167 3169
3181 3187 3191 3203 3209 3217 3221 3229 3251 3253 3257 3259 3271 3299
3301 3307 3313 3319 3323 3329 3331 3343 3347 3359 3361 3371 3373 3389
3391 3407 3413 3433 3449 3457 3461 3463 3467 3469 3491 3499 3511 3517
3527 3529 3533 3539 3541 3547 3557 3559 3571 3581 3583 3593 3607 3613
3617 3623 3631 3637 3643 3659 3671 3673 3677 3691 3697 3701 3709 3719
3727 3733 3739 3761 3767 3769 3779 3793 3797 3803 3821 3823 3833 3847
3851 3853 3863 3877 3881 3889 3907 3911 3917 3919 3923 3929 3931 3943
3947 3967 3989 4001 4003 4007 4013 4019 4021 4027 4049 4051 4057 4073
4079 4091 4093 4099 4111 4127 4129 4133 4139 4153 4157 4159 4177 4201
4211 4217 4219 4229 4231 4241 4243 4253 4259 4261 4271 4273 4283 4289
4297 4327 4337 4339 4349 4357 4363 4373 4391 4397 4409 4421 4423 4441
4447 4451 4457 4463 4481 4483 4493 4507 4517 4523 4547 4549 4561 4567
4583 4591 4597 4603 4621 4637 4639 4643 4649 4651 4657 4663 4673 4679
4691 4703 4721 4723 4729 4733 4751 4759 4783 4787 4789 4793 4799 4801
4813 4817 4831 4861 4871 4877 4889 4903 4909 4919 4931 4933 4937 4943
4951 4957 4967 4969 4973 4987 4993 4999 5003 5009 5011 5021 5023 5039
5051 5059 5077 5081 5087 5099 5101 5107 5113 5119 5147 5153 5167 5171
5179 5189 5197 5209 5227 5231 5233 5237 5261 5273 5279 5281 5297 5303

5309 5323 5333 5347 5351 5381 5387 5393 5399 5407 5413 5417 5419 5431
5437 5441 5443 5449 5471 5477 5479 5483 5501 5503 5507 5519 5521 5527
5531 5557 5563 5569 5573 5581 5591 5623 5639 5641 5647 5651 5653 5657
5659 5669 5683 5689 5693 5701 5711 5717 5737 5741 5743 5749 5779 5783
5791 5801 5807 5813 5821 5827 5839 5843 5849 5851 5857 5861 5867 5869
5879 5881 5897 5903 5923 5927 5939 5953 5981 5987 6007 6011 6029 6037
6043 6047 6053 6067 6073 6079 6089 6091 6101 6113 6121 6131 6133 6143
6151 6163 6173 6197 6199 6203 6211 6217 6221 6229 6247 6257 6263 6269
6271 6277 6287 6299 6301 6311 6317 6323 6329 6337 6343 6353 6359 6361
6367 6373 6379 6389 6397 6421 6427 6449 6451 6469 6473 6481 6491 6521
886 2

2.1 ()

6529 6547 6551 6553 6563 6569 6571 6577 6581 6599 6607 6619 6637 6653

6659 6661 6673 6679 6689 6691 6701 6703 6709 6719 6733 6737 6761 6763
6779 6781 6791 6793 6803 6823 6827 6829 6833 6841 6857 6863 6869 6871
6883 6899 6907 6911 6917 6947 6949 6959 6961 6967 6971 6977 6983 6991

6997 7001 7013 7019 7027 7039 7043 7057 7069 7079 7103 7109 7121 7127

7129 7151 7159 7177 7187 7193 7207 7211 7213 7219 7229 7237 7243 7247

7253 7283 7297 7307 7309 7321 7331 7333 7349 7351 7369 7393 7411 7417
7433 7451 7457 7459 7477 7481 7487 7489 7499 7507 7517 7523 7529 7537
7541 7547 7549 7559 7561 7573 7577 7583 7589 7591 7603 7607 7621 7639
7643 7649 7669 7673 7681 7687 7691 7699 7703 7717 7723 7727 7741 7753

7757 7759 7789 7793 7817 7823 7829 7841 7853 7867 7873 7877 7879 7883
7901 7907 7919 7927 7933 7937 7949 7951 7963 7993 8009 8011 8017 8039
8053 8059 8069 8081 8087 8089 8093 8101 8111 8117 8123 8147 8161 8167
8171 8179 8191 8209 8219 8221 8231 8233 8237 8243 8263 8269 8273 8287
8291 8293 8297 8311 8317 8329 8353 8363 8369 8377 8387 8389 8419 8423
8429 8431 8443 8447 8461 8467 8501 8513 8521 8527 8537 8539 8543 8563

8573 8581 8597 8599 8609 8623 8627 8629 8641 8647 8663 8669 8677 8681
8689 8693 8699 8707 8713 8719 8731 8737 8741 8747 8753 8761 8779 8783

8803 8807 8819 8821 8831 8837 8839 8849 8861 8863 8867 8887 8893 8923
8929 8933 8941 8951 8963 8969 8971 8999 9001 9007 9011 9013 9029 9041

9043 9049 9059 9067 9091 9103 9109 9127 9133 9137 9151 9157 9161 9173
9181 9187 9199 9203 9209 9221 9227 9239 9241 9257 9277 9281 9283 9293
9311 9319 9323 9337 9341 9343 9349 9371 9377 9391 9397 9403 9413 9419

9421 9431 9433 9437 9439 9461 9463 9467 9473 9479 9491 9497 9511 9521
9533 9539 9547 9551 9587 9601 9613 9619 9623 9629 9631 9643 9649 9661
9677 9679 9689 9697 9719 9721 9733 9739 9743 9749 9767 9769 9781 9787

9811 9817 9829 9833 9839 9851 9857 9791 9803 9859 9871 9883 9887 9901
3

(abstract class). , .
,
.
- (alpha channel). ,
. 8
.
(animation). , .
(antialiasing).
,
, , .
(boolean type). , :
(true) (false).
(clipboard). ,
.
. ,
, .
(expression). , ,
.
(world coordinate).
, .
(color depth). ,
, . ,
8 256 .
(double-buffering). ,
(
), .
(header file). , ,
.
. hpp, h, , hh, hxx
.
(internationalization). 8.
, / .
888 3

,
,
.
(interface). ,
.
(Graphic Device Interface, GDI).
Windows, .
(interator). , ,
.
(class). .
class struct.
(component).
.
, .
(container). , .
(context). .
(TrueType font). ,
, ,
.
(metafile). ,
.
(method). ,
.
(polygon).
.
(Modal dialog). ,
.
(plug-in). ,
.
.
(Non modal dialog). ,
, .
(object). .
- (child object). ,
, (-).
- (parent object). ,
, , -
(child object).
(object hierarchy). ,
.
(clipping). ,
.
889

(palette). , .
(enumeration). ,
.
(pixel). , .
,
.
(primitive). : ,
.
(prototype). ,
.
(process). .
(image, bitmap). ,
.
(coordinate system). ,
.
(signal). , .
(slot). , .
(event). ,
.
(string). .
(texture). - ,
, .
(file format). . ,
BMP, GIF, JPG.
(template). , .
(font). ,
.
Drag & drop. .
GNU (GNU's Not UNIX). , GNU UNIX.
, .
(GPL).
GPL (GNU Public License). GNU.
HTML (HyperText Markup Language ).
. ,
, . .
HSV (Hue, Saturation, Value , , ).
, ( ),
() ().
8. internationalization (. ).
18 , (i) ()
1 8 .
890 3

LZW (Lempel-Ziv-Welch). , , ,
GIF.
MDI (Multiple Document Interface).
.
MIME (Multipurpose Internet Mail Extensions). ,
, ,
.
, , ,
drag & drop.
OpenGL (Open Graphic Library). ,
Silicon Graphics.
RGB (Red, Green, Blue). ,
: , .
RGBA (Red, Green, Blue, Alpha). , ,
- ().
(XPixMap). .

.
4

FTP- - :
ftp://ftp.bhv.ru/9785977533461.zip.
www.bhv.ru.
() .
. Windows,
Mac OS X Linux, Qt Creator :
Windows:
qmake
make

Mac OS X:
qmake -spec macx-g++; make

Linux:
qmake; make

!!!
Qt 5.3 .

Qt,
:
https://qt-project.org/downloads.

. 4.1 .

4.1.


chapterOI 1.

chapter02
Hello
2:
, Hello, World

Counter

,
892 4

4.1 ()

chapter03 3:

Librarylnfo Qt

chapter05 5:

Background ;

MouseCursor ;

ScrollArea

chapter06 6:

AddStretch ,
;

Calculator ,
(QGridLayout);

HBoxLayout
,
(QHBoxLayout);

Layout

;

(QSplitter);
Splitter

Stretch ;
VBoxLayout ,

chapter07 7:

(QLabel);
Label

LabelBuddy
;

LabelPixmap
;

LCD ,
(QLCDNumber);

Progress
(QProgressBar)
chapter08 8\

ButtonGroup ;

ButtonPopup ;

Buttons
(QPushButton);
CheckBox (QCheckBox);

RadioButton
(QRadioButton)
893

4.1 ()

chapter09 9:
Dial (QDial);
ScrollBar (QScrollBar);
Slider (QSlider)
chapterlO 10:
DateTimeEdit
(QDateTimeEdit);
LineEdit
(QLineEdit);
SpinBox (QSpinBox);
TextEdit ,
(QTextEdit);
Validator ,
(QValidator)
chapterl 1 11:
ComboBox
(QComboBox);
IconMode ;
ListWidget
(QListBox);
TableWidget
(QTableWidget);
TabWidget (QTabWidget);
ToolBox (QToolBox);
TreeWidget
(QTreeWidget)
chapter12 12:
FileSystemModel
QFileSystemModel;
Explorer ,
QFileSystemModel;
HierarchicalModel ,
QStandartltemModel ;
IntListModel
;
ProxyModel
;
Roles ;
SelectionSharing
;
SimpleDelegate ,
;
TableModel ;
WidgetAndView

894 4

4.1 ()

chapter13 13:

WidgetPalette

chapter14 14:

MouseEvent ;

ResizeEvent

chapter15 15:

EventFilter

chapter16 16:

EventChange , ;

EventSimulation

chapter18 18:

CompositionModes ;
ConicalGradient ;

LinearGradient ;

PainterPath ;

RadialGradient ;

GraphicsEffect

chapter19 19:

ImageDraw
(Qlmage)
;

Window ,
;

TranslucentBackground ;
ScanLine

chapter20 20:

DrawText ;

GradientText ,
;

ElidedText
chapter21 21:

CustomGraphicsView
;

CustomGraphicsView


895

4.1 ()

chapter22 22:

Movie , (QMovie);
ColorAnimation ;

EasingCurves ;

States

chapter23 23:

OGLDraw ,
;

OGLPyramid
,
OpenGL;

OGLQuad OpenGL
chapter24 24:

Printer ,
QPrinter

chapter25 25:

CustomWidget
,

chapter26 26:

;
AppStyle

CSSStyle ;
CustomStyle ,
;

Styles Qt
chapter27 27:

SoundPlayer
(QMediaPlayer);

VideoPlayer ,
QMediaPlayer

chapter28 28:

Session (QSession);

Settings , (QSettings)

chapter29 29:

Drag ,
;

Drop ,

896 4

4.1 ()

chapter31 31:

ContextMenu ;
Menu ;

TearOffMenu ,
chapter32 32:

InputDialog ,
;

MessageBoxes ;

StandardDialogs
chapter33 33:
HelpBrowser , ;
WhatsThis ,
;
CustomToolTip
chapter34 34:

StatusBar ;
ToolBar
(QToolBar);
MDI MDI- ();
SDI ;

SplashScreen ,
(QSplashScreen)
chapter35 35:

SystemTray ;
ScreenShot
chapter36 36:

FileFinder
,
QDir;

FileSystemWatcher
chapter37 37:

BlinkLabel , (QTimer);

Clock ,
(QDateTime)
chapter38 38:

Process ,
(QProcess);

ThreadEvent ;

ThreadSignal ;

ThreadTimer -

897

4.1 ()

chapter39 39:

Client Server ,
QTcpServer QTcpSocket;

Downloader
QNetworkAccessManager;

TcpCIient TcpServer TCP- TCP-


;

UdpCIient UdpServer UDP- UDP-


QUdpSocket
chapter40 40:

XmlDOMRead , XML-
DOM;

XmIDOWrite ,
XML- DOM ;

XmlSAXRead XML- SAX;

XmlSreamReader XML-
QXmlStreamReader;

XQuery QXmlQuery
QtXmlPatterns
chapter41 41:

, ;
SQL

SQLQueryModel ;
SQLTableModel QSqlTableModel;
SqlRelationTableModel
QSqlRelationTableModel
chapter42 42:

DynLib ;
Plugin
chapter43 43:

WinAPI Windows;

MacButton Cocoa
chapter44 44:

MyForm , Qt Designer
chapter45 45:

DataDrivenTest ;

GuiTest ;
TestLib
898 4

4.1 ()

chapter46 46:

SimpleView WebBrowser
WebKit
chapter49 , 49:

ZweiMaIZwei Qt Script
chapter52 52,
Qt-, :

Debug
Qt Script;

SignalAndSlots
Qt Script;

Turtle ,
Qt Script
chapter53 53:

HelloQML Qt Quick-
chapter54 54,
:

CustomElement ;

Controls
QML;

Dialogs

;

OneControl
QML;

IdRefence ;

OnWidthAndHeight
;

Properties ;
Rectangle
chapter55 55,
:

Anchors Ancors2 ;
AnchorsOver ;

AnchorsStretch
;

Margins ;
Gridt Row
Grid Row;

RowLayout
RowLayout;
899

4.1 ()

chapter56 56, :

Borderlmage
;

Canvas ;

Gradients ;

Image

chapter57 57, :

Button ButtonAlternative ,
MouseArea;

EnterAndExit HoverEvent
. MouseArea;

Keyslnput ;

MouseArea MouseArea;

Navigation

;

;
Signals

Textlnput ;

TwoTextEdits

chapter58 58,
:
BehaviorAnimation ;
ColorAnimation ;

NumberAnimation ;
ParallelAnimation, SequentialAnimation
;

RotationAnimation ;
PropertyAnimation ;

State ;

Transition
chapter59 59,
-:

Flickable ;

GridView ;

ListView ;

PathViewLine
( );

PathViewQuad
(-);

XMLModel XML-
900 4

4.1 ()

chapter60 60,
QML C++:

QMLCPPUsage QML- Qt;

Calculation C++ QML;

ImageProvider C++
QML;

CPPExtension QML C++


common
Exaples.pro
readme.txt

DOM 29, 589


Double buffering 238, 275
_FILE_ 770 Drag 423
_LINE_ 770 Drag & Drop 173, 244, 422, 423
Drop 423

ActionScript 723 E
Android 667 emit 60, 63
Antialiasing 274, 280, 350 empty() 92
Apple 636 Enabled 122
Arthur 274 end() 92
ASCII 235, 881
F
Firing interval 535
Backing Store 1 23 fixqt4headers.pl 706
begin() 92 Flat Button 157
bi-level 310 foreach 96, 1 84
Bit map 297 forever 584
BMP 297 Form UI
Break points 82 0 direct approach 650
0 inheritance approach 651
c 0 multiple inheritance approach 652
FTP 563
C++ 635
Call Stack 703
Callback functions 55 G
clear() 92 GCC 636
Clipboard 421 GDB 80, 696
CMYK 270 0 attach 83
Cocoa 638 9 break 83
Collision detection 322 0 clear 83
Color roles 227 9 continue 83
constBeginQ 92 9 delete 83
constEnd() 92
9 detach 83
count() 92
9 disable 83
Critical section 554
9 enable 83
CSS 27,389, 667, 671
9 help 83
9 : 389
9 next 83
9 quit 83
D 9 run 83
Dashboard 667 9 step 83
Data Compression 518 0 tbreak 83
datagram 561 0 until 83
Deadlock 557 GDI 632
desktop 50 GIF 297, 298, 336
Disabled 122 GL_COLOR_BUFFER_BIT 355
DisplayRole 214 GL COMPILE 362
902

GL DEPTH BUFFER BIT 355 insert() 92


GL FLAT 355, 361 instaceof 743
GL LINE LOOP 358 iPad 636
GL LINE STRIP 358 iPhone 636, 667
GL LINES 358 iPodtouch 636
GL POINTS 358 isEmpty() 92
GL POLYGON 358 iTunes 666, 667
GL QUADS 355, 358, 362
GL SMOOTH 355 J
GL TRIANGLE FAN 362
GL TRIANGLE STRIP 358 JavaScript 667, 723
GL TRIANGLES 358 Joint Photographic Experts Group 298
glBegin() 355 JPEG 297, 298
GLbyte 351 JSON 744
glCallList() 361
glClear() 355
glClearColorQ 354
KDE 502, 667
glColor() 355
Key 411
GLdouble 351
Key Value 411
glEnd() 355
Konqueror 667
glEndList() 362
GLenum 351
GLfloat 351 L
glFrusturn() 361 Layout 1 3 1
glGenListsQ 362 Layout managers 131
GLint 351 lconvert 444
glLoadldentityO 354 LIBS 636
glMatrixMode() 354, 361 link 79
glNewList() 362 Linux 640
glOrthoQ 354 Look&Feel 50, 376
glPointSize() 359 Release 435, 444
glShadeMode() 361 lupdate 435, 437, 444
glShadeModel() 355 LZW 298
GLshort 351
GLubyte 351 M
GLuint 351
GLushort 351 Mac OS X 74, 502, 636, 666
glVertex() 355 Mac OS 640
glViewPortQ 354, 361 macdeployqt 297, 607, 618, 623
GNOME 502 Mail 667
Google 667 makefile 72
Graphics Interchange Format 298 - 74
Graphicsltem: dragLeaveEventQ 328 MDI 28, 489, 493, 501
GraphicsLineltem 325 Memory leak 134
GUI 32, 119 Memory mapped files 5 1 8
Menu Extras 502
MFC 56
H Microsoft Visual Studio 80
HSV 267, 269 MIME 422, 667, 668
HTML 178, 666, 667 MinGW 636, 677
MNG 297, 298, 336
MOC 57, 59, 77, 78
1 Modelview matrix 354
ICQ 502 Motif 56
IDE 677 Multiple Document Window Interface 489, 501
903

N Q PROPERTY 54
Q UINT16 87
Normal Button 157 Q UINT32 87
NSButton 638 Q UINT64 87
NSString 639 Q UINT8 87
NSSwitchButton 638 Q WS MACX707
Q WS WIN 707
0 Q WS XI 1 707
QABS() 86
Objective C 635 QAbstactScrollArea 205
Objective C++ 631, 635 QAbstractAnimation 339
ODF (OpenDocument Format) 178 0 pause)) 339
OpenGL 350 0 setLoopCount)) 340
0 355 0 start)) 339-342
6 356 0 stateChanged)) 339
OpenOffice.org. 178 0 stop)) 339
QAbstractButton 156
P 0 clicked)) 156
PBM 297 0 icon)) 156
PDF 365 0 iconSize)) 156
PGM 297 0 isChecked)) 157, 165
Phonon 705, 708 0 isDown)) 157
Pixmap Button 1 58 0 isEnabled)) 157
PlainText 178 0 pressed)) 156
PNG (Portable Network Graphics) 297, 298 0 released)) 157
PNM 297 0 setChecked)) 157, 161
PostScript 178 0 setDown)) 157
PowerPC 708 0 setEnabled)) 157
PPM 297 0 setlcon)) 156
Progress bar 150 0 setlconSize)) 156
Projection matrix 354 0 setText)) 156
0 text)) 156
Q 0 toggled)) 157
Q ASSERT() 83 0 clicked)) 157
QAbstractGraphicsShapeltem 325
Q CHECK PTR() 83
QAbstractltem
Q DECLARE INTERFACE)) 623
Q DECLARE METATYPE 757 0 SingleSelection 191
Q EXPORT PLUGIN 707 QAbstractltemDelegate 208
Q EXPORT PLUGIN2 707 QAbstractltemModel 204
Q INTI 6 87 0 data)) 210, 214
Q INT32 87 0 index)) 210
Q INT64 87 QAbstractltemView 191, 205
Q INT8 87 0 DoubleClicked 206
Q INTERFACES)) 627 0 model)) 224
Q INVOKABLE 716, 866 0 MultiSelection 191
Q OBJECT 57, 77 0 NoEditTriggers 206
Q OS AIX631 0 NoSelection 191
Q OS FREEBSD 631 0 SelectedC licked 206
Q OS IRIX 631 0 selectionModel)) 206
Q OS LINUX 631 0 setEditTriggers)) 205
Q OS MAC 631 0 setltemDelegate)) 208
Q OS SOLARIS 631 0 setRootlndex)) 212
Q OS WIN32 631 0 setSelectionMode)) 191
Q OS WIN64 631 0 setSelectionModel)) 206
904

QAbstractListModel 204 0 isSessionRestored() 419


QAbstractPrintDialog 0 processEvent() 522, 534
0 fromPage() 368 0 restoreOverrideCursor() 126
6 toPage() 368 0 saveState() 418
QAbstractProxyModel 205 0 setDoubleClicklnterval!) 240
QAbstractScrollArea 128 0 setFont()316
0 cornerWidget() 128 0 setPalette() 230
0 horizontalScrollBar() 128 0 setQuitOnLastWindow() 503
0 setViewPort() 325 0 setStyle() 378, 381
0 verticalScrollBar() 128 0 setStyleSheet() 389
0 viewport() 128 0 startDragDistance() 424
QAbstractSlider 166 QAudioFormat
6 setMaximum() 166 0 setChannels() 708
0 setMinimumO 166 0 setFrequency!) 708
0 setOrientation() 166, 401 QBasicTimer 539
0 setPageSteps() 167 0 isActive() 539
0 setRange() 166, 401 0 start!) 539
6 setSingleStepO 167 0 stop!) 539
6 setTrackingO 167 0 timerld!) 539
6 setValue() 167, 168, 405 qBinaryFind() 107
6 sliderChange() 166 QBitArray 99
6 sliderMoved() 401 0 operator[ ] 99
0 sliderPressed() 167 0 setBit() 99
0 sliderReleasedQ 167 0 testBit() 99
0 value() 167 QBitmap 310
QAbstractSocket 561 o fiiio 3ii
0 ConnectedState 584 qBlue() 269, 302
0 waitForBytesWritten() 583 qBound() 86
0 waitForConnected() 583 QBoxLayout 132
0 waitForDisconnected() 583 0 addLayout!) 137, 138
0 waitForReadyRead() 583 0 addSpacing!) 133
QAbstractSpinBox 184 0 addStretch() 134
QAbstractTableModel 204 0 BottomToTop 133
QAbstractTransition 0 insertLayout() 133
0 addAnimation() 347 0 insertSpacing() 133
QAction 482 insertStretch() 133
0 addAction() 496 0 insertWidget() 133
0 setEnabled() 448 6 LeftToRight 133
0 triggered!) 496 RightToLeft 133
qAlpha() 269 0 setMargin() 138
QAndroidStyle 378 0 TopToBottom 133
QAnirnationGroup 339 QBrush 227, 278
0 addAnimation() 341 QBuffer 428,515,518
QApplication 0 buffer!) 5 1 9
0 alertQ 50 0 setBuffer() 5 1 9
0 applicationDirPath() 520 QByteArray 98, 423, 428, 567
0 applicationFilePath() 520 0 fromBase64() 99
6 beep() 398 0 toBase64() 99
0 clipboard!) 421 QCanvasRectangle
0 closeAllWindows!) 496 0 setRect() 326
0 commitData!) 418, 419 QCheckBox 160
0 desktop!) 507 0 setNoChange() 160
0 installFilterQ 255 0 setTristate() 160
905

QChildEvent 244 0 startDocument() 595


added() 244 0 startElement() 595
removed() 244 QContextMenuEvent
QClipboard 421 0 globalPos() 450
dataChanged() 421 qCopy() 107
image() 422 qCopyBackward() 107
mimeData() 422 QCoreApplication 48, 85, 235, 250, 256
pixmap() 422 0 arguments!) 526
setlmage() 421 0 exec() 46, 235, 247
setMimeData () 421 0 exit() 46
setPixmap() 421 0 installFilter() 255
setText() 421 0 installTranslator() 440, 441
text() 422 0 notify!) 255
QCloseEvent 244 0 postEvent() 247, 256, 258, 551
QColor 227, 267 0 processEvents() 250
alpha() 268 0 quit() 3 1 4
alphaFQ 268 0 sendE vent() 247, 256, 551
6 blue() 268 0 setApplicationName() 41 1, 418
6 blueF() 268 0 setOrganisationName() 41 1
0 colorO 126 0 setOrganizationName() 41 8
6 colorl 126 qCount() 107
0 darker() 273 QCursor 124
6 getHsv() 270 QDataStream 567
QDate 196, 531
6 getRgb() 269
0 green() 268 0 addDays() 532
0 currentDate() 532
0 greenF() 268
0 day() 531
6 isValid() 462
0 dayOfWeek() 532
6 lighter!) 273
0 dayOfYear() 532
0 red() 268
0 daysInMonth() 531
6 redF() 268
0 daysln Year)) 531
6 rgb() 269
0 daysTo() 532
0 setHsv() 270
0 fromString!) 532
6 setRgb() 269
0 month!) 531
QColorDialog 461
0 setDate() 53 1
getColor() 461
0 weekNumber() 532
QComboBox 198, 205
0 year() 53 1
6 activated)) 198
QDateStream 529
6 addltemO 198 QDateTime 534
0 currentlndex() 198 0 currentDateTime!) 186
0 editTextChanged() 198 QDateTimeEdit
6 setDuplicatesEnabled() 198 0 dateTimeChanged!) 186
6 setEditable() 198, 199 QDB2 606
6 setModel() 205 qDebug!) 84-86, 699
0 setValidator() 187 QDeclarativeView 864
QCommonStyle 377, 385 qDeleteAll() 107
QCOMPAREO 658, 662, 663 QDesktopServices 5 11
qCompressO 98, 5 1 8 0 MoviesLocation 511
QConicalGradient 279 0 storageLocation() 5 11
QContentHandler QDesktopWidget 507
0 characters!) 595 0 isVirtualDesktop!) 508
0 endDocument!) 595 0 numScreens() 508, 510
6 endElement() 595 0 primaryScreen)) 508
906

QDesktop Widget (.) 0 setContext() 591


resized() 508 0 toString!) 592
0 screen()510 QDomElement 590
0 screenCountChanged() 508 0 attribute!) 591
0 screenGeometryO 508 0 tagName()591
0 screenNumber() 508 0 text() 591
QDial 166, 170 QDomNode 590
setNotchesVisible() 170 0 firstChild!) 591
setNotchTarget() 170 0 nextSibling!) 591
0 setWrapping() 170 0 toElement!) 590
valueChanged() 171 0 traverseNode() 591
QDialog 453 QDomText 590
0 accept() 457 QDoubleValidator 187
0 Accepted 368, 454, 457 QDrag 424
6 exec() 455, 457 0 setMimeData() 430
0 hide() 454 0 setPixmap!) 425
0 isModal() 453 0 start!) 425
0 Rejected 454, 457 QDragEnterEvent 244
0 rejected!) 457 0 acceptProposedAction() 426
6 setModal() 453 QDragLeaveEvent 244
0 show() 454 QDragMoveEvent 244
QDir 515, 519 0 accept!) 427
0 absolutePath() 521 0 ignore!) 427
6 cd() 520 QDropEvent 244
6 cdUp() 520 QEasingCurve 343
0 count)) 520 0 CosineCurve 346
6 current!) 519, 521 0 InBack 345
0 currentPath() 212 0 InBounce 345
0 drives!) 519 0 InCirc 344
0 entryInfoList() 520 0 InCubic 344
0 entryList() 520, 523 0 InCurve 346
0 exists!) 520 0 InElastic 344
0 home() 519 0 InExpo 346
0 makeAbsolute!) 520 0 InOutBack 345
0 mkdir() 520 0 InOutBounce 345
0 rename!) 520 0 InOutCirc 344
0 rmdir() 520 0 InOutCubic 344
0 root() 5 1 9 0 InOutElastic 344
6 setFilter() 523 0 InOutExpo 342, 343
6 setSorting!) 523 0 InOutQuad 344
0 tempPath() 519 0 InOutQuart 345
QDirModel 205 0 InOutSine 346
QDockWidget 0 InQuad 343
0 setAllowedAreas() 485 0 InQuart 344
0 setFeatures() 485 0 InQuint 345
QDomAttr 590 0 InSine 345
6 setValue() 593 0 Linear 343
QDomDocument 0 OutBack 345
0 appendChild() 592 0 OutBounce 342, 345
0 createAttribute() 592, 593 0 OutCirc 344
0 createElement!) 592, 593 0 OutCubic 344
0 createTextNode() 592, 593 0 OutCurve 346
0 documentElementQ 591 0 OutElastic 344
907

9 OutExpo 343 9 Focusln 248


OutlnBack 345 9 FocusOut 248
9 OutlnBounce 346 9 FontChange 249
6 OutlnCirc 344 9 Hide 248
9 OutlnCubic 344 9 HideToParent 248
9 OutlnElastic 345 9 HoverEnter 249
OutlnExpo 344 0 HoverLeave 249
9 OutlnQuad 344 0 HoverMove 249
9 OutlnQuart 345 0 IconDrag 249
OutlnQuint 345 0 IconTextChange 249
9 OutlnSine 346 0 ignore!) 235, 245
9 OutQuad 344 0 InputMethod 249
OutQuart 345 0 KeyPress 248, 256, 259
9 OutQuint 345 0 KeyRelease 248, 256
OutSine 346 0 LanguageChange 249. 44 1
9 SineCurve 346 9 LayoutDirectionChange 249
qEqual() 108 9 LayoutRequest 249
QErrorMessage 471 9 Leave 248
9 message!) 471 9 LeaveWhatsThisMode 249
QEvent 234, 248 9 LocaleChange 249
9 accept!) 235, 245 9 MenubarUpdated 249
9 AccessibilityDescription 249 9 ModifiedChange 249
9 AccessibilityHelp 249 9 MouseButtonDblClick 248
9 AccessibilityPrepare 249 9 MouseButtonPress 248, 254
0 ActionAdded 249 0 MouseButtonRelease 248
9 ActionChanged 249 0 MouseMove 248
9 ActionRemoved 249 0 MouseTrackingChange 249
9 ActivationChange 249 0 Move 248
9 ApplicationActivated 249 0 None 248
9 ApplicationDectivated 249 0 Paint 248
9 ApplicationFontChange 248 0 PaletteChange 248
9 ApplicationLayoutDirectionChange 248 0 ParentAboutToChange 249
9 ApplicationPaletteChange 248 0 ParentChange 248
9 ApplicationWindowIconChange 248 0 Polish 249
9 ChildAdded 249 9 PolishRequest 249
9 ChildPolished 249 9 QueryWhatsThis 249
9 ChildRemoved 249 9 Quit 248
9 Clipboard 248 9 Resize 248
9 Close 248 9 Shortcut 249
9 ContextMenu 249 9 ShortcutOverride 248
9 Create 248 9 Show 248
9 DeferredDelete 248 9 ShowToParent 248
9 Destroy 248 9 ShowWindowRequest 249
9 DragEnter 248 9 SockAct 248
9 DragLeave 248 0 Speech 248
9 DragMove 248 0 StatusTip 249
9 DragResponse 249 0 Style 249
9 Drop 248 0 StyleChange 249
9 EnabledChange 249 0 TabletMove 249
9 Enter 248 0 TabletPress 249
9 EnterWhatsThisMode 249 0 TabletRelease 249
9 FileOpen 249 9 ThreadChange 248
908

QEvent (.) QFileSystemModel 21 1


Timer 248 QFileSystemWatcher 525
9 ToolBarChange 249 9 addPath() 525, 526
9 ToolTip 249, 474 9 directories!) 526
9 type() 235, 248 9 directoryChanged() 525, 526
9 UpdateLater 249 9 fileChanged() 525, 526
9 UpdateRequest 249 9 removePath() 525
9 User 247, 249 qFillQ 108
9 WhatsThis 249 qFind() 108
9 WhatsThisClicked 249 qFindChildren() 69
9 Wheel 248 qFindChildren<T>() 707
9 WindowActivate 248 QFleSystemWatcher
9 WindowBlocked 249 9 files!) 526
9 WindowDeactivate 248 QFocusEvent 238
9 WindowIconChange 248 QFont 316
9 WindowStateChange 249 QFontDatabase 316
9 WindowTitleChange 248 9 families!) 316
9 WindowUnblocked 249 QFontDialog 462
9 WinEventAct 249 9 getFont() 462
9 ZOrderChange 249 QFontlnfo 316
Loop 538 9 bold() 317
9 exec() 538 9 family!) 317
9 quit() 538 9 italic!) 317
qFatal() 84, 85, 86 QF ontMetrics 316,317, 320
QFETCH() 662 9 ascent!) 3 1 7
QFile 515, 517 9 boundingRect() 3 1 7
9 close()491 9 charWidth() 3 1 7
9 exists()517 9 descent!) 3 1 7
9 fileName() 517 9 elidedText() 320
9 flush() 517 9 height!) 317
9 open() 490 9 leftBearing!) 317
9 setNameO 5 1 7 9 lineSpacing() 317
QFileDialog 458 9 rightBearing!) 317
9 getExistingDirectory() 458, 460 9 width!) 317
9 getOpenFileName() 458, 490 QFormLayout 138
9 getOpenFileNames() 458 QFrame 127
9 getSaveFileName() 458, 491 9 Box 128
QFilelnfo 515, 523 9 drawFrame!) 374
9 absoluteFilePath() 524 9 HLine 128
9 baseName() 524 9 NoFrame 128
9 completeSuffix() 524 9 Panel 128
9 created!) 524 9 Plain 127
9 TileNameO 524 9 Raised 127
9 filePath() 524 9 setFrame!) 174
9 isDir() 523 9 setFrameStyle() 127, 374
9 isExecutable() 524 9 setLineWidth 174
9 isFile() 523 9 setLineWidth!) 128,374
9 isHidden() 524 9 setMidLineWidth!) 128
9 isReadableQ 524 9 Sunken 127
9 isSymLink() 523 9 VLine 128
9 isWriteable() 524 9 WinPanel 128
9 lastModified() 524 QFtpl 707
9 lastRead() 524 QFusionStyle 378
909

QFuture 558 QGraphicsSimpleTextltem 325


isFinished() 558 QGraphicsView 325, 864
isPaused() 559 9 centerOn() 324
isRunningO 558 9 setMatrix() 325
isStartedQ 559 9 setScene() 325
pause() 559 9 show() 326
qFuzzyCompareO 86 qGreen() 269, 302
QGL 352 QGridLayout 132, 138
QGLColormap 352 0 addWidget() 141
QGLContex 352 0 setColStretch() 138
QGLFormat 352 0 setRowStretch() 138
QGLPixelBuffer 352 0 setSpacing() 138, 139
QGLWidget 352 QGroupBox 162
0 context() 352 0 setCheckable() 164
0 format() 352 0 setChecked() 164
0 initializeGL() 352 QGtkStyle 378
0 paintGL() 352 QGuiApplication
9 qglClearColor() 354 9 setOverrideCursor() 125
0 resizeGL() 352 qHash() 105
QGradient QHash<K.T> 105
0 setColorAt() 3 1 9 QHashlterator 93
QGraphicsEffect 294 QHBoxLayout 133, 135, 137
0 draw() 294 QHeaderView 206
QGraphicsEllipseltem 325 QHelpEvent 474
QGraphicsItem 322 QHideEvent 245
0 dragEnterEvent() 328 QHostAddress
9 dragMoveEventQ 328 0 LocalHost 584
9 dropEvent() 328 QHttp 707
9 hide() 325 QIBASE 606
9 paint() 325 Qlmage 300
9 rotate() 325 0 converToFormatO 300
9 scaled 325 0 format() 300
9 setAcceptDrops() 328 0 Format_ARGB32 300
9 setEnable() 325 0 Format_ARGB32_Premultiplied 300
9 setMatrix() 325 0 Format_Index8 300
9 setPos() 325 0 Format_Invalid 300
9 setTransformO 333 9 Format_Mono 300
9 shear() 325 9 Format_MonoLSB 300
9 show() 325 9 Format_RGB32 300
9 translate() 325 9 invertPixels() 304
QGraphicsItemAnimation 339 9 load() 301
QGraphicsItemGroup 325 9 mirrored() 306
QGraphicsPixmapItem 325 9 pixel() 301
QGraphicsPolygonltem 325 9 save()301
QGraphicsProxyWidget 333 9 scaled() 305
QGraphicsRectltem 325 9 scanLine() 302
9 setBrushQ 326 9 setColor() 301
9 setPen() 325 0 setPixelQ 301
QGraphicsScene 322 QlmagelOPlugin 621
9 addltem() 324 QInputDialog 463
9 itemAt() 324 0 getDouble() 463
9 items() 324 0 getlnteger() 463
QGraphicsSceneEvent 0 getltem() 463
9 widget() 328 0 getTextQ 463
910

QInputEvent 0 setPixmap*) 146, 149, 340, 510


modifiers*) 235, 236, 241 0 setText*) 146, 148, 241. 246, 405, 427, 536
qlnstallMsgHandler*) 84 QLayout 132
QIntValidator 187 0 addLayout*) 132
QIODevice 515 0 addWidget*) 132
0 Append 516 0 removeWidget*) 132
6 atEnd() 5 1 6 QLayoutltem 132
0 close*) 516 QLCDNumber 153
6 flush*) 584 0 Bin 153
0 getChar()516 0 Dec 153
6 isOpen()517 0 display*) 154
6 isReadable*) 517 0 Filled 153
0 isWriteable*) 5 1 7 0 Flat 153
6 NotOpen516 0 Hex 153
6 open*) 516 0 Oct 153
0 openMode*) 516 0 Outline 1 53
0 pos()516 0 overflow*) 153
6 read*) 516, 517 0 setBinMode*) 153
6 read All*) 516, 518 0 setDecMode*) 153
0 readData*) 516 0 setHexMode*) 1 53
6 readLine*) 516 0 setMode*) 153
0 Readonly 516 0 setNumDigits*) 153
6 Read Write 516 0 setOctMode*) 153
0 seek*) 516 0 setSegmentStyle*) 141, 153
0 size*) 516 0 setSmallDecimalPoint*) 153
6 Text 516 0 valueChanged*) 154
6 Truncate 516 QLibrary 619
6 Unbuffered 516 0 resolve*) 620
0 write*) 516, 517, 584 QLibrarylnfo 87
0 writeData*) 516 QLine 266
0 WriteOnly 516 QLinearGradient 279
QltemDelegate 208 QLineEdit 173
0 createEditor*) 209 0 clear*) 572
0 setEditorData*) 209 0 copy*) 175
0 setModelData*) 209 0 cut*) 175
QltemSelectionModel 206 0 isRedo Available*) 175
0 currentChanged*) 207 0 isUndoAvailable*) 175
6 currentColumnChanged*) 207 0 maxLength*) 175
0 currentRowChanged*) 207 0 Password 173
0 select*) 207 0 paste*) 175
0 selectedlndexes*) 207 0 redo*) 175
0 selectionChanged*) 207 0 returnPressed*) 173
QKeyEvent 235, 259 0 setEchoMode*) 173
0 key*) 236 0 setMaxLength*) 175
0 text*) 236 0 setReadOnly*) 173
QLabel 146, 176 0 setText*) 173, 572
0 linkActivated*) 150 0 setValidator*) 187
0 setAlignment*) 146, 241 0 text*) 173
6 setBuddy*) 149, 174, 188 0 textChanged*) 173
<> setMovie*) 146,337 0 undo*) 175
0 setNum*) 169 QLineF 266
0 setOpenExternalLinks*) 150 QLinkedList<T> 101
911

QLinkedListlterator 93 QMacStyle 378


QList<T> 99 QMainWindow 480
9 at() 100 9 addDockWidget() 485
9 move() 100 9 addToolBar() 483
9 removeFirst() 100 9 central Widget() 481
9 removeLastQ 100 9 menuBar() 480
9 swap() 1 00 0 setCentralWidget() 481, 492, 496
9 takeAt() 100 0 statusBar() 481
9 takeFirst() 100 qmake 74, 76, 79
9 takeLast() 100 0 OBJECTIVE SOURCES 636
9 toSet() 100 QMap<K,T> 103
9 toStdList() 100 QMapIterator 93
9 toVector() 100 QMax() 86
QListlterator 93 QMdiArea 493
9 findNext() 93 0 cascadeSubWindowsQ 493
9 findPrevious() 93 0 setHorizontalScrollBarPolicyO 496
9 hasNext() 93 9 setVerticalScrollBarPolicyO 496
9 hasPrevious() 93 9 subWindowList() 493
9 next() 93 9 titleSubWindows() 493
9 peekNext() 93 QMediaPlayer 399
9 peekPrevious() 93 9 duration() 402, 406
9 previous() 93 9 durationChanged() 402
9 toBack() 93 9 fromAscii() 706
9 toFront() 93 9 pause() 404
QListView 206 9 PausedState 404
9 setFlowQ 192 9 play() 404
9 setSelectionMode() 195 0 PlayingState 404
9 TopToBottom 192 9 positionChangedQ 402
QListWidget 189, 224 0 setMedia() 399, 402
9 addltem() 189 0 setPositionQ 405
9 clear() 189 0 setVideoOutput() 408
9 currentltem() 191 0 setVolume() 401
9 insertltem() 189 0 state() 404
9 itemChanged() 191 0 stateChanged() 402
9 itemClicked() 191 0 stop()401
9 itemDoubleClickedO 191 9 StoppedState 404
9 itemSelectionChanged() 191 9 toAscii() 706
9 itemWidget() 190 QMenu 445, 504
9 selectedltemsO 191 9 addAction() 1 59, 448
9 setItemWidget() 190 9 addSeparator() 448
9 sortItems() 192. 196 9 clear() 499
QListWidgetltem 189 9 exec() 450
9 clone() 189 9 setChecked() 448
9 operator<() 193 9 setTearOffEnabled() 449
9 setFlags() 191 9 triggered() 450
9 setlconQ 190 QMessageBox 466
QLocate 0 Abort 468
9 name() 442 0 aboutQt() 470
9 system() 442 0 Cancel 468
qLowerBoundQ 108 0 Critical 468
QMacCocoaV iew 0 critical) 469
9 setCocoaView() 638 0 Default 468
QMacCocoaViewContainer 637 0 Escape 468
912

QMessageBox (.) 9 Borderlmage.top 816


() 467 9 color 790, 795
6 Ignore 468 9 ColorAnimation 837, 838
6 Information 468 9 ColorAnimation.duration 839
6 No 468 9 ColorAnimation.from 838
NoAll 468 9 ColorAnimation.running 839
9 NoButton 468 9 ColorAnimation.to 838
9 Noicon 468 9 Column 807, 856, 860
6 Ok 468 9 Component 856
9 Question 468 9 date 790, 795
6 Retry 468 9 Easing.InBounce 850
9 setButtonText() 468 0 Easing.InCirc 850
9 setIcon() 468 0 Flickable 855
9 setlconPixmapQ 468 0 Flickable.contentHeight 855
0 setText() 468 0 Flickable.contentWidth 855
9 Warning 468, 469 9 font 818
6 Yes 468 9 font.bold818
6 YesAll 468 9 font.pixelSize 818
QMetaObject 70 9 Gradient 817, 857
QMimeData 9 GradientStop 817
9 hasFormatO 426, 432 9 GradientStop.color 817
6 setColorDataQ 422 9 GradientStop.position 817
9 setData() 423, 428 9 Grid 807
6 setHtml() 423 9 Grid.columns 810
0 setlmageDataQ 422, 428 9 Grid.rows810
9 setText() 423 9 GridView 786, 855, 858. 860
6 setUrls() 423 9 Image 786, 813-815, 839, 841, 856
6 urls() 427 9 Image.rotation 814, 815
QMimeSource 422 9 Image, scale 814
QMin() 86 9 Image, smooth 814
QML 777, 779 0 Image, source 813
9 action 790, 795 0 Image.transform 815
9 anchors 800, 802, 803 0 Image.x814
9 anchors.bottom 804 0 Image.y814
9 anchors.bottomMargin 806 9 int 790, 795
9 anchors.centerln 803 9 Item 786, 787, 791, 856
9 anchors.fill 802, 803, 822 9 Item.anchors 788
9 anchors.horizontalCenter 801. 804 9 Item.height 787, 788
9 anchors.left 804, 805 9 Item.id 788
9 anchors. leftMargin 806 9 Item.onHeightChanged 790
9 anchors, right 804, 805 9 Item.onWidthChanged 790
9 anchors.rightMargin 806 9 Item.parent 788, 800
9 anchors.top 804 9 Item.position 788
9 anchors.topMargin 806 9 Item, state 846
9 anchors.verticalCenter 801, 804 9 Item.transitions 848
9 Animation.Infinite 836, 843 9 Item. width 788
9 Behavior 841 9 Item.x 787. 788
9 bool 790, 795 9 Item.y 787, 788
9 Borderlmage 786, 816, 827 9 JavaScript 845
9 Borderlmage.bottom 816 0 KeyNavigation.down 832
9 Borderlmage. left 816 0 KeyNavigation. left 832
9 Borderlmage.right 816 0 KeyNavigation.right 832
913

9 KeyNavigation.tab 831 9 Qt Creator 782


KeyNavigation.up 832 9 real 790, 795
9 Keys.onDownPressed 833 9 Rectangle 781, 786, 787, 792, 800, 814. 856,
9 Keys.onLeftPressed 833 865
9 Keys.onPressed 833 9 Rectangle. border.color 787
9 Keys.onRightPressed 833 9 Rectangle.color 787, 788, 831
9 Keys.onUpPressed 833 9 Rectangle.gradient 8 1 7
list 790, 795 9 Rectangle.opacity 804
ListElement 852 9 Rectangle.radius 787
9 ListModel 852, 853 9 Rectangle.rotation 817
9 ListModel. insert() 853 9 Rectangle.scale 817
9 ListModel.move() 853 0 Rectangle.smoth 787
0 ListModel.remove!) 853 0 Rotation 815
9 ListView 786, 855, 856, 857 0 Rotation.angle 815
9 ListView.delegate 856 0 RotationAnimation 837, 839. 844
9 ListView.footer 857 9 RotationAnimation.Clockwise 839, 844
9 ListView.header 857 9 RotationAnimation.Counterclockwise 839
9 ListView. highlight 857 9 RotationAnimation.direction 844
9 ListView. model 857 9 RotationAnimation.Shortest 839
9 MouseArea 781, 822, 84 1 , 844
9 Row 807, 808, 856
9 Scale 815
9 MouseArea.acceptedButtons 823
9 Scale.xScale 815
9 MouseArea.hoverEnabled 824
9 Scale.yScale 815
9 MouseArea. mouse 823
9 SequentialAnimation 842, 844
9 MouseArea. mouseX 826
9 signal 825
9 MouseArea. mouseY 826
9 string 790, 795
9 MouseArea.onClicked 827, 844, 847
9 Text 786, 791, 792, 800, 818, 827, 857, 865
9 MouseArea.onEntered 824 9 Text.text 793
9 MouseArea.onMousePositionChanged 826, 841
9 TextEdit 829
9 MouseArea.onPressed 823, 827, 828 9 Textlnput 829
9 MouseArea.onReleased 823, 827, 828 0 Textlnput.focus 829, 830
9 NumberAnimation 837, 838, 841, 844 0 time 790, 795
9 OnExited 824 0 Transition 848
9 origin.x815 0 Transition.to 848
9 origin.y815 9 Transtion.from 848
9 ParallelAnimation 842 9 url 791, 795
9 ParallelAnimation. loop 843 9 vector3d 791, 795
9 Path 861 9 WebView 786
9 Path.startY 861 9 XmlListModel 853, 854
9 PathAttribute 862 9 XmlListModel.query 855
9 PathQuad 862 9 XmlListModel.source 854
9 PathView 855, 860, 861 9 XmlRole 855
9 PathView.pathltemCount 861 QModellndex 210
9 property 790 9 isValid() 210
9 PropertyAnimation 836 QMouseEvent 233, 254, 258, 312
9 PropertyAnimation.duration 836 9 button!) 239, 254
9 PropertyAnimation.from 836 9 globalPos() 239
9 PropertyAnimation. loop 836 9 globalX() 239
9 PropertyAnimation. properties 836 9 globalY() 239
9 PropertyAnimation.target 836 0 pos() 239
9 PropertyAnimation.to 836 0 x() 239, 486
9 PropertyChanges 846 0 y() 239, 486
914

QMoveEvent 245 9 sender!) 61


oldPos() 245 9 setObjectName() 68
pos() 245 9 setParent() 68
QMovie 336 9 startTimer!) 535
6 NoRunning 336 9 thread!) 546
0 Paused 336 9 timerEvent() 243, 535
6 Running 336 9 timerldQ 535
9 setPausedQ 336 9 tr() 436, 437
9 setSpeedQ 336 qobject_cast<T> 54, 626
0 start)) 336 QObjectList 69
9 stateQ 336 QOCI 606
9 stop() 336 QODBC 606
QMultiHash<K,T> 105 QPaintDevice 274, 275, 364
QMultiMap<K,T> 104 QPaintEngine 274
QMutex 555 QPainter 274, 275
6 lock() 555 0 begin!) 275, 308
0 tryLock() 555 9 CompositionMode_SourceOver 291
6 unlock() 555 9 drawEllipse!) 308, 369
QMutexLocker 555 9 drawlmage() 304, 308
QMYSQL 606 9 drawLine() 368
QM- 440 9 drawPath() 289
QNetworkAccessManager 576, 585, 707 0 drawPicture() 286
QNetworkProxy 586 9 drawPixmap!) 761
6 setApplicationProxy() 586 9 drawPolyLine() 282
QNetworkReply 576 9 drawRect() 319, 368
6 downloadProgress() 576 9 drawText()318, 321, 369, 374
6 error() 576 9 end() 275, 308
9 finished!) 576 0 initFromQ 308
9 readyRead() 576 0 resetMatrix () 761
9 uploadProgress() 576 9 restore!) 277, 287
QNetworkRequest 576 0 rotate!) 287
QObject 53, 61,68, 252 0 save!) 277, 287
0 blockSignals() 63 0 scale)) 286
6 child!) 244 0 setBrush() 278, 369
9 childEvent() 244 0 setClipPath() 290
9 children!) 69 9 setClipRect() 290
6 connect!) 63, 66, 171, 455, 477 9 setClipRegion() 290
9 connect!) 142 9 setCompositionMode() 291
9 customEvent() 247 9 setFont() 318, 369
9 deleteLater() 566 0 setPen() 277, 369
6 disconnect!) 66 0 setRenderHint() 280, 308
6 dumpObjectlnfo!) 70, 85 9 setTransform() 288
9 dumpObjectTreeQ 70 9 shear!) 287
0 event!) 247, 248 9 translate!) 286, 761
0 eventFilter!) 252, 253, 259 9 viewport!) 368
9 findChild!) 69 QPainterPath 289
9 findChildren() 69 QPaintEvent 235, 238, 274
9 inherits!) 70 0 rect() 274
0 installEventFilter() 252, 253, 258 0 region!) 238, 274
9 killTimer!) 535 QPalette 227
9 moveToThread!) 546 0 Active 227
9 objectName!) 68, 85 0 Base 228
9 parent!) 69 0 BrightText 228
915

9 Button 228 QPointF 263


ButtonText 228 QPolygon 267
9 Dark 228 QPolygonF 267
Disabled 227 QPrintDialog 364, 460
9 Highlight 228 9 exec() 368
9 HighlightedText 228 QPrinter 178, 364
Inactive 227 9 AO 365
9 Light 228 9 A1 365
9 Link 228 A2 365
9 LinkVisited 228 0 A3 365
Mid 228 A4 365
A5 365
Midlight 228
A6 365
9 setBrush() 229
A7 365
setColor() 165,229
A8 365
Shadow 228
A9 365
9 Text 228
9 abort!) 365
Window 228
9 BO 365
9 WindowText 228
9 B1 365
QParallelAnimationGroup 34 1
QPauseAnimation 339 9 B2 365
QPen 277 B3 365
9 setCapStyleQ 277 9 B4 365
9 setColor() 277 9 B5 365
9 setJoinStyle() 277 9 B6 365
9 setWidthQ 277 9 B7 365
QPicture 286 9 B8 365
QPictureFormatPlugin 621 9 B9 365
QPixmap 308 0 BIO 365
9 createHeuristicMask( ) 31 3 C5E365
9 defaultDepth() 309 0 Color 364
9 drawPixmap() 309 1 OF, 365
9 fill() 761 0 DLE365
9 grabWindow() 510 0 Executive 365
9 load() 149, 309 0 Folio 365
9 rotate()761 0 Grayscale 364
9 save() 309, 460 9 HighResolution 178
9 scaled!) 510 9 Landscape 364
9 setMask() 310, 31 1 9 Ledger 365
QPixmapCache 310 9 Legal 365
9 fmd() 310 9 Letter 365
9 insert!) 310 9 NativeFormat 178
QPlaintTextEdit 175 9 newPage() 368
QPluginLoader 623, 625 9 PdfFormat 365
9 instance!) 623, 625 9 Portrait 364
9 unload!) 623 9 PostScriptFormat 178
QPoint 263 9 setColorMode() 364
9 isNull() 264 9 setDocName!) 365
9 manhattanLength!) 264 0 setFromTo() 364
9 rx() 264 0 setMinMaxQ 368
9 setX() 264 0 setNumCopies() 364
9 setY() 264 0 setOrientation() 364
9 x() 264 0 setOutputFileName() 178, 365
9 y() 264 9 setOutputFormatQ 365
916

QPrinter (.) 0 width() 266


setPageSize() 365 0 x() 266
6 Tabloid 365 0 y() 266
QProcess 540 QRectF 266
0 CrashExit541 qRed() 269, 302
0 error()541 QRegExp 111, 187
6 exitStatis() 541 QRegion
0 finished)) 541 0 intersected() 291
0 NormalExit 541 0 subtracted() 291
0 readAllStandardError() 541 0 united()291
0 readAllStandardOutput() 541 0 xored() 29 1
0 readyRead() 541 QResizeEvent 245
0 readyReadStandardError.() 541 0 oldSize() 245
0 readyReadStandardOutput() 541, 542 0 size() 245
0 start() 541, 542 QRgb 269, 302
0 started() 541 qRgbO 269
QProgressBar 150 qRgba() 269, 302
0 reset() 152 qRound() 86
0 setOrientation() 151 QScriptContext 756
6 setProgress() 171 argument() 756
6 setRange() 152 0 argumentCount() 756
6 setValue() 152 QScriptEngine 721. 756, 757
QProgressDialog 464 0 evaluate() 720, 721,757
0 canceled() 464 0 globalObject() 757
6 reset() 465 0 newArray() 759
6 setAutoClose() 465 0 newObject() 758
0 setAutoReset() 465 0 newQObject() 721, 757, 764
0 setMinimumDuration() 464 0 newVariant() 758
0 setProgessQ 464 QScriptEngineDebugger 770
0 setTotalSteps() 464 0 attachTo() 770
6 setWindowTitle() 465 QScriptValue 721, 756
6 wasCanceled() 465 0 isError() 757
QProperty Animation 339 0 setProperty() 72 1
QPSQL 606 QScrollArea
QPushButton 142, 157 0 removeChild() 129
6 clicked() 64, 1 42, 31 4, 457, 477 0 setWidget() 129
6 setFlat() 158 0 widget() 1 29
6 setMenu() 159 QScrollBar 166. 169
QQmlContext 866 sliderMoved() 167
0 setContextPropertyO 867 0 valueChanged() 167, 372
QQmlEngine 866 Q Semaphore 556
QQueue<T> 101 0 acquire() 556
QQuickWidget 866 0 release() 556
0 rootContextQ 866 0 tryAcquire() 556
QRadialGradient 280 QSequentialAnimationGroup 341
QRect 122, 266 QSessionManager 418
0 height() 266 0 allowInteraction() 419
0 setHeightQ 266 0 cancel!) 419
0 setSize() 266 0 setRestartFIintO 419
6 setWidth() 266 QSet<T> 105
6 setX() 266 QSettings
0 setY() 266 0 beginGroup() 412,416
6 size() 266 0 endGroup() 412,415
917

readEntry() 41 5 9 setWrapping() 185


remove()412 9 stepDown() 185
setValue() 411 9 stepUp() 185
value()412 9 value() 185
writeEntry() 416 0 valueChanged() 185
QShowEvent 245 QSplashScreen 487
QSignalMapper 495 9 finish() 487
QSignalTransition 347 9 show() 487
QSize 264 0 showMessage() 487
0 height() 265 QSplitter 144
9 isNull() 264, 266 QSqlDatabase 606
9 rheight() 265 0 addDatabase() 607
9 rwidth() 265 0 lastError() 608
9 scale() 265 0 open() 608
9 setHeight() 265 0 setDatabaseName() 608
9 setWidth() 265 9 setHostName() 608
9 width() 265 9 setUserName() 608
QSizeF 264 9 tables() 608
QSizeGrip 481 QSqlDriver 605
QSizePolicy QSqlDriverCreator<T*> 605
9 Expanding 372 QSqlDriverCreatorBase 605
9 Fixed 371 QSqlDriverPlugin 605, 621
9 Ignored 372 QSqlError 606, 608
9 Maximum 371 9 isValid() 612
9 Minimum 371 9 text() 608
9 MinimumExpanding 371 QSqlField 606
9 Preferred 371 9 length()611
QSlider 166, 167 0 name() 6 11
9 NoTicks 167 0 type()611
9 setTicklntervalQ 168 0 value()611
9 setTickmarksQ 169 QSqllndex 606
9 setTickPosition() 167 QSQLITE (QSQLITE2) 606
9 TicksAbove 167 QSqlQuery 606, 608
9 TicksBelow 167 0 bindValue() 609
9 TicksBothSides 167 0 exec() 608
QSocket 9 first() 608
9 connectToHost() 569 9 last() 608
qSort() 108 9 next() 608
QSortFilterProxyModel 222 9 prepare() 609
9 setFilterRegExpO 222 9 previous() 608
QSound 398 9 record()611
9 isFinishedQ 398 9 seek() 608
9 loopsRemaining() 398 9 setQuery() 612
9 play() 398 9 size() 609
9 setLoopsQ 398 QSqlQueryModel 606
9 stop() 398 9 lastError() 612
QSpinBox QSqlRecord 606, 61 1
9 setButtonSymbols() 185 0 contains() 61 1
9 setPrefix() 185 0 count()611
9 setRange() 185 0 fleld() 61 1
9 setSpecialValueText() 185 0 fieldNameO 61 1
9 setSuffix() 185 0 indexOf() 6 11
9 setValue() 185 QSqlRelation 615
918

QSqlRelationalTableModel 606, 615 9 replace()110


QSqlRelationTableModel 9 setNum() 11 1
0 setRelation() 615 9 split() 522
QSqlResult 605 9 toLower()110
QSqlTableModel 0 toUpper()110
0 OnManualSubmit 614 9 635, 639
QSqlTableModel 606, 613 QStringList
0 OnFieldChange 614 0 join() 11 1
0 OnRowChange 614 0 split() 111
0 removeColumn() 613 QStringListModel 204, 867
0 setEditStrategy() 614 QStyle 377
QSqlTableModel 0 drawComplexControl() 382
0 submitAll() 614 0 drawControl() 382
6 revertAll() 614 0 drawPrimitiveO 382
0 rowCount() 614 0 polish() 386
0 setFilter() 614 9 State_MouseOver 208
0 setSortQ 614 9 unpolish() 386
0 insertRowQ 614 QStyleFactory 622
6 setData()614 9 create()381
6 removeRowsQ 615 QStyleOptionViewItem 208
QSslSocket QStylePainter
6 waitForEncryptedQ 583 0 initFromO 388
qStableSort() 108 QStylePlugin 621
QStack<T> 101 9 create()621
6 pop() 101 QSvgRenderer 338
6 push() 101 9 repaintNeeded() 338
6 top() 101 QSvgWidget 338
QStackedWidget 127 0 load() 338
0 addWidget() 127 qSwap() 108
6 indexOfQ 127 QSyntaxHighlighter 176, 179, 181
0 setCurrentIndex() 127 0 highlightBlock() 179
0 setCurrentWidget() 127 0 previousBlockStateQ 182
QStandardltemModel 204 0 setCurrentState() 182
QState 347 QSysInfo 639
6 addTransition() 347 9 MacintoshVersion 640
assignProperty() 347 9 MV_SNOWLEOPARD 640
QStateMachine 347 9 WindowsVersion 640
6 setlnitialStateQ 347 9 WV_CE_5 640
6 start() 347 9 WV_CE_6 640
QStatusBar 485 9 WV_VISTA 640
9 addPermanentWidget() 485 0 WV_WINDOWS7 640
6 addWidget() 485, 486 9 WV_XP 640
9 cleaMessage() 485 QSystemTraylcon 503, 504
9 removeWidget() 485 9 setContextMenu() 503
0 showMessage() 485, 492, 496 0 setIcon() 503, 507
QString 110 0 setToolTip() 503, 505
9 append() 11 0 0 showMessage() 503, 506
9 arg() 609 Qt 48
0 containsQ 187, 460 0 AlignBottom 147
9 isEmpty() 1 10, 490 0 AlignCenter 241
9 length()110 0 AlignCenter 147
9 number() 11 1, 246 0 AlignHCenter 146
9 remove() 450 0 AlignJustify 146
919

9 AlignLeft 146 9 ForbiddenCursor 125


9 AlignRight 146 9 gray 272
AlignTop 146 9 green 272
AlignVCenter 147 9 Horizontal 166
9 AltModifier 235 9 HorPattern 278
6 ArrowCursor 124 9 IbeamCursor 125
AscendingOrder 192 9 IgnoreAspectRatio 265, 305
6 Autoconnection 62, 547 9 ISODate 532
9 BackgroundColorRole 214 9 ItemlsUserCheckable 193
BDiagPattern 278 9 KeepAspectRatio 265, 305
6 black 272 9 KeepAspectRatioByExpanding 265
9 BlanckCursor 125 0 LeftButton 240
0 blue 272 0 lightGray 272
6 Checked 193 0 LinearGradientPattern 278
9 ClosedHandCursor 125 0 LocaleDate 532
0 color0 272, 310, 311 9 magenta 272
9 color 1 272, 310, 311 9 MidButton 240
9 ConicalGradientPattern 278 9 NoBrush 278
9 ControlModifier 235 9 NoButton 240
9 CrossCursor 125 9 NoModifier 235, 256
9 CrossPattern 278 9 NoPen 277
9 cyan 272 9 OpenHandCursor 125
9 darkBlue 273 9 PointingHandCursor 125
9 darkCyan 273 9 QueuedConnection 62
9 darkGray 272 9 RadialGradientPattern 278
9 darkGreen 273 9 red 272
9 darkMagenta 273 9 RightButton 240
9 darkRed 272 9 RoundCap 277
0 darkYellow 273 0 ShiftModifier 235
9 DashDotDotLine 277 0 SizeAllCursor 125
9 DashDotLine 277 0 SizeBDiagCursor 125
9 DashLine 277 0 SizeFDiagCursor 125
9 DecorationRole 214 0 SizeHorCursor 125
9 Dense1 Pattern 278 0 SizeVerCursor 125
9 Dense2Pattem 278 9 SolidLine 277
9 Dense3 Pattern 278 9 SolidPattern 278
9 Dense4Pattem 278 9 SplitHCursor 125
9 Dense5Pattem 278 9 SplitVCursor 125
9 Dense6Pattern 278 9 SquareCap 277
9 Dense7Pattern 278 9 SystemLocaleDate 532
9 DescendingOrder 192 9 TextColorRole 214
9 DiagCrossPattern 278 9 TextDate 532
9 DirectConnection 62 9 TextDontClip 318
9 DisplayRole 214 9 TextExpandTabs 318
9 DotLine 277 9 TextShowMnemonic 3 18
9 ElideLefit 321 9 TextSingleLine 31 8
9 ElideMiddle 321 9 TexturePattern 278
9 ElideNone321 0 Text Word Wrap 319
9 ElideRight 321 9 ToolTip 474
9 FDiagPattern 278 9 ToolTipRole 214
9 FlatCap 277 0 UpArrowCursor 125
9 FontRole214 0 VerPattern 278
920

Qt (.) Qt3Support 705


Vertical 151, 166 QTableView 206,613
WA_DeleteOnClose 498 QTableWidget 196, 224
WA_Hover 208, 386 0 setCellWidget() 196
6 WA_TranslucentBackground 313 0 setltem() 197
WaitCursor 125 QTableWidgetltem
WhatsThisCursor 125 0 clone() 196
6 WhatThisRole 214 0 setIcon() 196
6 white 272 0 setText() 196
WindowStaysOnTopHint 122 QTab Widget
0 yellow 272 0 addTab() 200
Qt 3 705 0 setCurrentIndex() 199
Qt 4 705 0 setTabEnabled() 199
Qt Assistant 72, 706 QTarnsform
Qt Creator 677, 679, 686, 696 0 rotate() 333
0 Locator 69 1 QtConcurrent 557
0 689 0 mapped() 559
0 694 0 run() 558
0 699 QTcpServer 563
0 688 QTcpSocket
0 689 0 connected() 569
0 684 0 connectToHost() 584
0 688 0 disconnectFromHostO 584
0 679 0 error() 569
Qt Designer 389, 642, 678, 681, 686 0 nextPendingConnection() 584
Qt Help 677 0 readyRead() 569
Qt Linguist 435, 438 0 waitForDisconnected() 584
Qt Quick 777 QtDebugMsg 84
Qt Script QTDS 606
6 Array 748 QTemporaryFile 519
QTest
0 arseFloat() 739
0 addColumn() 661
6 eval() 738
0 keyClick() 663
6 parseFloat() 727
0 keyPress() 663
6 parselnt() 727, 739
0 keyRelease() 663
6 sNaN() 739
0 mouseClick() 664
0 723
0 mouseDClick() 664
6 724
0 mouseMove() 664
6 748
mousePress() 664
6 Date 751
0 mouseReleaseO 664
6 Global 746
0 newRow()661
6 Number 746
QTEST_MAIN() 659, 663
6 String 747 QTestEventList 664
6 770 0 simulate() 664
0 724 qtestlib 708
6 747 QTextBrowser 476
0 747 0 backwardQ 477
6 727 0 backwardAvailable() 477
0 747 0 forward() 477
0 726 0 forwardAvailable() 477
6 725 0 home() 477
0 732 0 setSearchPath() 477
0 734 0 setSourceQ 477
921

QTextCodecPlugin 621 0 elapsed() 534


QTextCursor 175 0 fromString() 533
QTextDocument 178 0 hour() 533
6 redo() 176 0 minute() 533
0 undo() 176 0 msec() 533
QTextDocumentWriter 0 second() 533
0 setFileName() 178 0 setHMS() 533
0 setFormatQ 178 0 start() 534
QTextEdit 175 0 toString() 533, 566
0 clear() 175 QTimeLine 339
0 copy() 175 QTimer 339, 537
6 cut() 175 0 isActive() 537
0 deselect() 175 0 setlnterval() 537
0 document() 176 0 singleShot() 537
6 find() 176 0 stop() 537
0 insertFltml() 176 0 timeout() 537
0 insertPlainText() 176 QTimerEvent 243
0 paste() 175 QtMsgType 84
0 redoAvailable() 176 QtMultimedia 397
6 selectAHQ 175 QToolBar 483
0 selectionChanged() 175 0 addAction() 483
0 setDocument() 176 0 addSeparator() 483
6 setHtml() 175-177,450 0 addWidget() 483
6 setPlainText() 145, 175,490 QToolBox 200
0 setPlaintText() 176 0 addltem() 200
0 setReadOnly() 175 0 count() 200
6 text() 175 0 currentChanged() 200
0 textChanged() 175 0 insertltem() 200
0 textCursor() 176 0 removeItem() 200
0 toPlainText() 491 QTransform 333
0 undoAvailable() 176 0 scale() 333
0 translate() 333
0 zoomlnQ 176
QTranslator 435, 440
0 zoomOut() 176
0 load() 440
QTextStream 527
QTreeView 206
readAll() 490, 528
QTreeWidget 193, 224
0 readLine() 528 0 itemClicked() 195
0 setRealNumberPrecisionQ 528 0 itemDoubleClicked() 195
QtFatalMsg 84
itemSelectionChanged() 195
QtGui 706
QThread 547
0 setHeaderLabels() 194
0 exec() 535, 546 0 setItemExpanded() 194
0 setSortingEnabled() 195
0 exit() 546
QTreeWidgetltem 193
0 priority() 545
0 clone() 193
0 quit() 546
0 operator<() 196
6 run() 544
0 setDragEnabled() 195
0 setPriorityO 545
0 setIcon() 193
6 start() 544, 550
0 setText() 193
0 usleep() 550 QtScript 715
QTime 533 QtSvg 338
6 addMSecs() 533 QtUiTools 653
0 addSecs() 533 QtWarningMsg 84
0 currentTimeO 533 QtXmlPattems 599
922

QUdpSocket 572 QWebView 669, 671


bind() 572 9 load() 669, 674
9 readDatagrarn() 572 9 loadFinished() 671
ready Read() 572 9 loadProgress() 671, 673
9 writeDatagram() 572 9 stop() 673
QUiLoader 653 QWheelEvent 243
qUncompressQ 98, 518 9 buttons() 243
qUpperBound() 108 9 delta() 243
QUrl 669 0 globalPos() 243
0 fromLocalFileO 399 0 pos() 243
9 toString() 427 Q Widget 119, 130, 165, 236
QValidator 187 n setTabOrder() 144
9 Acceptable 187 0 activateWindow() 454
9 Intermediate 187 0 backgroundRole() 165
9 Invalid 187 0 close() 244
9 validate() 187 9 closeEvent() 245. 416, 504
QVariant 1 13 9 contextMenuEvent() 450
6 toInt() 218, 61 1 9 dragEnterEvent() 244, 426
9 toString() 61 1 9 dragLeaveEvent() 244
9 type() 11 3 9 dragMoveEvent() 244
9 typeName() 1 13 9 dropEvent() 244, 426, 427
9 typeToNameQ 1 13 9 enterEvent() 243
9 value<T>() 218 9 event() 236
Q V ariantAnimation 9 focusInEvent() 238
6 setDurationQ 340 9 focusOutEvent() 238
9 setEndValue() 340 9 geometry() 122
6 setKey ValueAt() 340 9 height() 122, 507
9 setStartValueQ 340 0 hide() 121, 245
QVBoxLayout 133, 136, 137 0 hideEvent() 245
QVector<T> 0 isEnabled() 122
9 data() 98 0 keyPressEvent() 235, 236
9 fill() 98 0 keyReleaseEvent() 235, 236
9 insert() 97 0 leaveEvent() 243
9 push_back() 98 0 mouseDoubleClickEvent() 122, 239, 240
9 reserve() 98 9 mouseMoveEvent() 122, 239, 241, 424, 432, 486
9 resize() 98 9 mousePressEvent() 122, 233, 239, 241, 247, 424
9 toList() 98 9 mouseReleaseEvent() 122, 239, 241
9 toStdVector() 98 9 move() 122
QVectorlterator 93
9 moveEventO 245
QVERIFY() 663
9 paintEvent() 238, 274, 374, 761
QVideoWidget 407
QWaitCondition 556
9 palette() 227
9 wait() 557 9 pos() 122
9 wakeAll() 557 9 raise() 454
9 wakeOne() 557 9 repaint() 238, 375, 761
qWarning() 84, 85, 86 9 resize() 123, 140, 240, 246
QWebHistory 671 9 resizeEvent() 245
9 back() 671 0 setAcceptDrops() 426, 431
9 canGoBack() 675 0 setAttribute() 208, 313
9 canGoForward() 675 0 setAutoFillBackground 123
9 clear() 671 0 setCursor() 127
9 forward()671 0 setEnabled() 122, 401. 477
QWebFIistoryltem 671 0 setFixedSizeQ 347, 761
923

9 setFont()316 9 name() 598


setGeometryO 1 19, 122 9 readNext() 598
9 setGraphicsEffect() 294, 340 9 text() 598
9 setMargin() 128 9 tokenString() 598
9 setMaskQ 311
9 setMinimumWidth() 152 R
9 setMouseTracking() 239
9 setObjectName() 429 RAD 642
9 setPalette() 123, 165, 229 Radio Button 161
RCC 78
9 setPixmap() 312
Reimp 607
9 setStyle() 378, 379
remove() 92
9 setStyleSheet() 389 Rendering context 350
9 setToolTip() 473 RGB 267, 268
9 setWindowFlags() 121
9 setWindowIconQ 498
9 setWindowTitle() 122, 429, 468, 498
s
9 show() 121, 140, 238, 240, 245, 356 Safari 667
9 showEvent() 245 SAX 29, 594
9 showFullScreenQ 356 Scalable Vector Graphics 338
9 size() 122 SDI 28, 489
9 sizeHint() 371, 639 shared data 1 14
9 sizePolicyO 371 Single Document Window Interface 489, 501
9 style() 382 singleshot 537
size() 92
9 update() 238
Skype 502
9 wheelEvent() 243
sortColumn() 196
9 width() 122, 507
Spacer 646
9 winld() 632 Splash Screen 487
9 x() 122 SQL 603
9 xl lEvent() 635 SQL-
9 y() 122 0 612
9 changeEvent() 442 0 615
QWindowsCEStyle 378 0 6 1 3
QWindowsMobileStyle 378 States 346
QWindowStyle 185,378 Step Into 701
QWindowsVistaStyle 378 Step Out 701
QWindowsXPStyle 378 Step Over 700
QWizard 465 STL 90, 95
QWizardPage 465 SVG 338. 667
9 setTitle() 465 systat 563
QWorkspace 706 System Tray 502
QXmlContentHandler 594
QXmlDefaultHandler 595
QXmlQuery 599 T
9 bindVariable() 599 TCP 561
9 evaluateToQ 599 9 568
9 isValid() 599 0 563
9 setQuery() 599 Tear-off menu 449
QXmlSimpleReader 594 Thread safety 555
9 setContenFlandler() 595 Toggle Button 157
QXmlStreamReader 597 Tool Tip 473
9 atEnd() 598 Top-level widget 1 19
9 errorStringO 598 Transitions 346
9 hasError() 598 TRANSLATIONS 438
924

Tristate Button 160 Windows API 56, 632


TS- 437, 438 Windows Notepad 489
Tulip 90 Workaround 715
typeof 743 Wrapper 718
typeof() 726 WYSIWYG 642

u X
UDP 562 XBM 297
0 572 XCode 74
UML 847 XHTML 667
Unicode 528 XML 29, 42, 587, 602, 667
URL 423 XML Query Language 599
XML- 588, 589
v 0 588
0 588
value() 92 0 590, 594
Viewport 354 0 588
VoIP 33 XPath 853
XPixmap 298
w 297, 298, 309
W3C 587 XQuery 599
Watches 702 0 concat() 601
Web 666 0 count() 602
WebKit 666-670 0 empty() 602
Web- 666-668, 670, 671 0 for 601
Web- 666, 668 0 order by 601
Whats this 475 0 return 601
Widgets 119 0 where 60 1
windeployqt 623
Windows 640, 666


LZW 298 97
107 557
336 50, 376
274 119, 130
524 0 1 84
0 227
0 11 9
79 0 162
603 0 157
0 603 0 131
0 603 0 227
0 603 0 227
0 604 0 161
421 0 391
925

189
170

160 503
41 6
507
123
166
354
199
447 193
539 : 310
533 150
473 56
159 677
198 250
696
435
666
31 6 623
480 92
421, 436, 446 0 Java 93
279, 817 0 STL 94
0 279 0 93, 95
0 279
0 280
322, 324

0 324 278
235
0 325

0 446
0 446
53 1 7 18
238, 275 - 562
481 411,420
562 0 41 1, 420
452 0 412
0 About Qt 470 140, 156, 157, 165
0 463 0 157, 158
0 458 0 162
0 461 0 156
0 462
0 157
0 157
0 469
0 156
0 465
0 157, 158
0 453
0 158
0 460
0 160
0 454 131
0 452 : link 79
0 469 279
0 464
0 454 0 91, 102
0 466 0 91, 96
0 470 9 1
0 471
617 0 350
484 0 274
926

450
187

82, 83, 701 502
554 322
699 825
31 0 114
489, 501
173

279 0 354
699 0 487
0 702
: 418

310 178
288 79, 80
338 0 GDB80, 83
316
0 696

449
0 354 290
0 354 101
346 697
131 0 699
445
0 698
0 445
0 699
0 445, 448
0 697
0 445
0 445, 450
0 447
0 445, 449 271, 273
54, 70
57, 77 0 502
286 0 200, 482
79 437
228 161, 165
489, 287
501 173, 422, 423
544 346
105 277
203, 852 297
0 XML853 157
0 21 0 288
0 222
0 852 0 473
Qt 46 0 475
397 390, 391
124, 239,310 0 391
554 109
167
267
169
146 : 543
411 112
205, 324
927

109
Qt Assistant 72, 706 101, 140
Qt Designer 75, 389, 642 0 127
Qt Linguist 438 377
540 0 378
679 0 382
540 0 392
() 266 1 10
266 0 485
324
184, 185
50
280
144 196
264 54, 535, 537, 539
127 0 535
111, 187 0 535
175 1 10

0 274, 280 0 663
0 291 0 658
() 78, 671 0 66 1
238, 281
0 658
0 282
0 658
0 283
657
0 28 1 263
0 283 699


54 124
274, 280, 350 170
389 552
556
: TCP 563 0 fixqt4headers.pl 706
98,518
0 lconvert 444
54, 58, 233
697 0 lrelease 435, 444
554 0 lupdate 435, 437, 444
476 0 macdeployqt 297, 607, 618, 623
411 0 qmake 74, 76, 79
288 0 78
103 0 reimp 607
54, 58, 60, 233
233, 252, 327, 535, 551
561
0 561
0 561 0 make 74
561 0 524
495 0 524
108 0 524
391 0 524
99, 189 0 525
0 198 0 74, 75, 79
0 193 75
928

(.)
524
267
75, 76 0 271
h 76 267
mm 63 1 0 CMYK 267, 270
444 0 HSV 267, 269
D pro 74, 79 0 RGB 267, 268
qrc 78 271
D qss 389 703
ts 444
ui 75
xlf 444

800 679
54, 252 316
160, 165, 447 0 316
238 316
123

0 BMP 297

0 GIF 298 140, 153
0 JPEG 298 325, 786
0 PDF 365 0 786
PNG 298 0 788
XML 587, 602
298
55

737 :
0 738 0 UML847
0 737 0 XML 599

X
104

Вам также может понравиться