Вы находитесь на странице: 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.