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

-

-
2012

681.3.068+800.92C++
32.973.26-018.1
68

.
68

Qt 4.8. C++. .:
-, 2012. 912 .: . ( )
ISBN 978-5-9775-0736-3
Windows, Linux Mac OS X Qt 4.8. ,
, ,
. Qt Creator.
c Qt Quick QML.
Qt 4, , .
.

681.3.068+800.92C++
32.973.26-018.1

:

.
.

31.03.12.
70 1001/16. . . . . 73,53.
2000 .
"-", 190005, -, ., 29.
""
199034, -, 9 , 12/28

ISBN 978-5-9775-0736-3

., 2012
, "-", 2012

.................................................................................. 3
................................................................................................................. 5
..................................................................................................................... 6
.............................................................................................................................. 6

.......................................................................................................................... 16
I. QT .............................................................................................. 25
1. Qt ......................................................................... 27
Qt ............................................................................................................... 27
Qt ...................................................................................................................................... 28
Qt .......................................................................................................... 30
QtCore ...................................................................................................................... 30
QtGui ........................................................................................................................ 31
QtNetwork ................................................................................................................ 32
QtXml ....................................................................................................................... 32
QtSql ......................................................................................................................... 33
QtOpenGL ................................................................................................................ 33
QtWebKit.................................................................................................................. 33
QtSvg ........................................................................................................................ 33
Qt3Support................................................................................................................ 33
........................................................................................................................................... 33

2. .................................................................... 34
....................................................................................................... 36
................................................................................................................................. 39
..................................................................................................................................... 41
............................................................................................................ 42
......................................................................................................... 46
.............................................................................................. 47
........................................................................................................ 49
........................................................................................................................................... 50

IV

3. Qt ...................................................................................................... 51
IDE ..................................................................................... 51
Qt Assistant ..................................................................................................................................... 51
qmake .............................................................................................................................. 51
Qt ................................................................................................... 55
MOC .............................................................................................. 56
RCC .......................................................................................................... 57
Qt- ................................................................................................................... 57
............................................................................................................................ 58
GDB (GNU Debugger) .......................................................................................... 59
....................................................................................................... 62
Qt......................................................................................................... 63
Qt ...................................................................................................... 65
........................................................................................................................................... 66

4. ............................................................................. 67
................................................................................................................... 68
...................................................................................................................................... 70
Java ......................................................................................................... 70
STL......................................................................................................... 71
foreach ........................................................................................................ 73
................................................................................................... 73
QVector<T> .............................................................................................................. 74
QByteArray .......................................................................................... 75
QBitArray .............................................................................................. 76
QList<T>, QLinkedList<T> ..................................................................................... 76
QStack<T> .................................................................................................................... 78
QQueue<T> ............................................................................................................ 79
......................................................................................................... 79
QMap<K,T>, QMultiMap<K,T> ............................................................................ 80
QHash<K,T> QMultiHash<K,T> ............................................................................ 82
QSet<T>............................................................................................................. 82
..................................................................................................................................... 84
............................................................................................................................ 85
...................................................................................................................................... 85
.............................................................................................................................. 86
........................................................................................................ 86
............................................................................................................................................ 86
......................................................................................................... 88
QVariant ........................................................................................................ 90
...................................................................................... 91
........................................................................................................................................... 92

II. ................................................................ 93
5. .............................................. 95
QWidget ............................................................................................................................... 95
........................................................................................... 98
......................................................................................... 99
...................................................................................................... 99
............................................................................................... 100

............................................................................................................................. 103
............................................................................................................................................ 103
........................................................................................................ 104
......................................................................................................................................... 106

6. ...................... 107
(layout managers) ............................................................................... 107
................................................................... 109
QBoxLayout ...................................................................................................... 109
QHBoxLayout ............................................................. 111
QVBoxLayout ................................................................. 112
..................................................................................................... 113
QGridLayout ................................................................................ 114
................................................................................................ 120
QSplitter .................................................................................................................. 120
......................................................................................................................................... 121

7. ............................................................................. 122
....................................................................................................................................... 122
.................................................................................................................. 126
............................................................................................................. 129
......................................................................................................................................... 131

8. , .......................................................... 132
. QAbstractButton ................................................................. 132
....................................................................................... 132
...................................................................................... 132
.................................................................................................................. 133
......................................................................................................................................... 133
......................................................................................................................................... 136
............................................................................................................................ 137
................................................................................................................... 138
......................................................................................................................................... 141

9. .................................................................................. 143
QAbstractSlider.................................................................................................................. 143
........................................................................................................ 143
.......................................................................................................... 143
................................................................................................................... 144
...................................................................................... 144
...................................................................................................................................... 144
....................................................................................................................... 146
................................................................................................................................. 147
......................................................................................................................................... 149

10. ......................................................................................... 150


.................................................................................................... 150
........................................................................................................................... 152
....................................................................................................................... 155
(syntax highlighting) ........................................................................ 155

VI

.................................................................................... 162
................................................................................................................................ 162
.......................................................................................... 163
............................................................................................................................ 164
......................................................................................................................................... 165

11. ..................................................................................... 167


........................................................................................................................... 167
.............................................................................................................. 167
....................................................................................... 169
................................................................................ 169
.............................................................................................................. 169
........................................................................................................ 170
................................................................................................................ 171
........................................................................................................ 174
....................................................................................................................................... 174
.................................................................................................................. 176
........................................................................................................................................ 177
.................................................................................................... 178
......................................................................................................................................... 179

12. - .................................................. 180


................................................................................................................................... 181
................................................................................................................................. 181
..................................................................................................................... 183
........................................................................................................... 184
................................................................................................................................. 186
.......................................................................................................................... 188
............................................................................................................... 188
........................................................................................................................... 192
................................................................................... 194
(Proxy model) ........................................................................ 200
- ............................................................................... 202
......................................................................................................................................... 204

13. ........................................... 205


......................................................................................................................................... 208

III. ...... 209


14. ...................................................................................................... 211
................................... 213
........................................................................................................... 213
QKeyEvent ........................................................................................................ 213
QFocusEvent ..................................................................................................... 216
. QPaintEvent ..................................... 216
.................................................................................................................... 217
QMouseEvent .................................................................................................... 217
QWheelEvent ..................................................................................................... 221
enterEvent() leaveEvent() ........................................................................... 221

VII

. QTimerEvent............................................................................... 221
(drag & drop) ............................................................................. 222
QDragEnterEvent ............................................................................................. 222
QDragLeaveEvent ............................................................................................. 222
QDragMoveEvent ............................................................................................. 222
QDropEvent ...................................................................................................... 222
................................................................................................ 222
QChildEvent ...................................................................................................... 222
QCloseEvent ..................................................................................................... 222
QHideEvent ....................................................................................................... 223
QMoveEvent ...................................................................................................... 223
QShowEvent ...................................................................................................... 223
QResizeEvent .................................................................................................... 223
............................................................................... 224
event() ................................................................................................ 225
........................................................................... 228
......................................................................................................................................... 229

15. ..................................................................................... 230


................................................................................................... 230
......................................................................................................................................... 233

16. .......................................................... 234


......................................................................................................................................... 237

IV. ............................................................................... 239


17. ..................................................... 241
....................................................................................................................... 241
.................................................................................................................................... 241
.............................................................................................................. 242
.................................................................................................................... 244
...................................................................................................................... 244
................................................................................................................................ 245
.............................................................................................................................................. 245
Qolor ....................................................................................................................... 245
RGB ........................................................................................................ 246
HSV ......................................................................................................... 247
CMYK ..................................................................................................... 248
................................................................................................................................ 249
.................................................................................................... 250
......................................................................................................................................... 251

18. .............................. 252


QPainter............................................................................................................................. 253
.............................................................................................................................. 255
...................................................................................................................................... 255
.................................................................................................................................... 256
.................................................................................................................................... 257
(Anti-aliasing) ......................................................................................... 258

VIII

.................................................................................................................................... 259
.................................................................................................................. 259
................................................................................................................. 260
........................................................................... 261
.......................................................................................... 261
........................................................................................................... 264
............................................................................................ 264
....................................................................................................................... 265
............................................................................................................... 266
................................................................................................................................ 266
...................................................................................................................................... 266
........................................................................................... 266
(painter path) ...................................................................................... 267
.................................................................................................................................... 268
(composition mode) .................................................................................... 269
................................................................................................................ 272
......................................................................................................................................... 274

19. ........................................................................... 275


................................................................................................... 275
BMP ........................................................................................................................ 275
GIF .......................................................................................................................... 276
PNG ........................................................................................................................ 276
JPEG ....................................................................................................................... 276
XPM........................................................................................................................ 276
- .................................................................................. 278
QImage....................................................................................................................... 278
QImage .............................................................................. 285
- ...................................................................................... 286
QPixmap .................................................................................................................... 286
QPixmapCache .......................................................................................................... 287
QBitmap ..................................................................................................................... 288
QPixmap ................................................................................... 288
........................................................................... 290
......................................................................................................................................... 292

20. ................................................................................. 294


................................................................................................................... 296
......................................................................................................................................... 299

21. ................................................................... 300


............................................................................................................................................ 301
............................................................................................................................. 301
........................................................................................................................................ 302
....................................................................................................................................... 305
................................................................................... 311
......................................................................................................................................... 313

22. .................................................................................................... 314


QMovie............................................................................................................................... 314
SVG- ............................................................................................................................... 316

IX

.......................................................................... 317
............................................................................................................. 320
......................................................................................... 324
......................................................................................................................................... 327

23. OpenGL ....................................................................................... 328


OpenGL ................................................................................................... 328
Qt OpenGL ............................................................................................... 330
OpenGL- ................................................................................................ 330
OpenGL- ................................................................... 333
OpenGL ............................................................................................. 334
................................................................................................................... 337
......................................................................................................................................... 341

24. ........................................................................................ 342


QPrinter ............................................................................................................................. 342
......................................................................................................................................... 347

25. ................................ 348


..................................................................................................... 348
......................................................................................................................................... 353

26. ................................................................................. 354


....................................................................................................................... 356
................................................................................................... 360
................................................................... 361
.......................................................................... 361
........................................................ 362
............................................................ 362
QStyle ....................................................................... 366
........................................................................... 366
.......................................................................................................... 367
................................................................................................... 368
................................................................................................... 369
................................................................................................................................. 370
......................................................................................................................................... 374

27. .............................................................................................................. 375


............................................................................................................... 375
................................................................................. 376
, ............................................................................. 376
......................................................................................................................................... 379

28. ............................................................................................. 380


Phonon ................................................................................................. 380
Phonon ................................................................................................................... 381
............................................................................................................................. 384
..................................................................................................... 386
......................................................................................................................................... 389

V. .............................................................. 391
29. ........................................................ 393
................................................................................................................... 400
......................................................................................................................................... 402

30. ............................................................ 403


.............................................................................................................................. 403
........................................................................................................................... 404
drag ................................................................................................................... 406
drop ................................................................................................................... 408
................................................................. 410
......................................................................................................................................... 415

31. ...................................................... 417


.................................................................... 417
lupdate ........................................................................................................................... 419
Qt Linguist ................................................................................................................ 420
lrelease. , .............................................. 421
....................................................................... 423
...................................................................................................... 425
......................................................................................................................................... 426

32. ........................................................................................... 427


........................................................................................................................... 427
.......................................................................................................................... 431
...................................................................................................................... 432
......................................................................................................................................... 433

33. ....................................................................................... 434


.......................................................................................... 434
QDialog ............................................................................................................................. 435
............................................................................................. 435
.......................................................................................... 436
........................................................................ 436
.................................................................................................. 440
....................................................................................... 440
............................................................................... 442
.......................................................................................... 443
...................................................................................... 444
....................................................................................................... 445
................................................................................................ 446
................................................................................................... 447
..................................................................................................... 448
.................................................................................. 450
............................................................................... 450
.......................................................................................... 451
............................................................................................ 452
About Qt .................................................................................................. 452
............................................................................................... 453
......................................................................................................................................... 453

XI

34. ......................................................................... 455


............................................................................................................ 455
" " .................................................................................................................... 457
(Online Help) .................................................................................................. 458
......................................................................................................................................... 461

35. SDI- MDI- ........................................................ 462


QMainWindow .......................................................................................... 462
QAction .............................................................................................................. 463
................................................................................................................. 464
............................................................................................................................................. 466
........................................................................................................................ 467
.............................................................................................................................. 469
SDI- MDI- ............................................................................................................. 471
SDI- .................................................................................................................. 471
MDI- ................................................................................................................. 475
......................................................................................................................................... 483

36. (Desktop)............................................................................. 484


................................................................................................................. 484
............................................................................................................................. 489
.................................................................................................... 493
......................................................................................................................................... 493

VI. QT ....................................................... 495


37. , -............... 497
-. QIODevice ................................................................................................... 497
. QFile .......................................................................................... 499
QBuffer ....................................................................................................................... 500
QTemporaryFile......................................................................................................... 501
. QDir............................................................................................... 501
...................................................................................... 502
. QFileInfo .................................................................................... 505
? ............................................................................................................... 505
................................................................................................................ 506
........................................................................................... 506
............................................................................................... 506
............................................................................................... 506
...................................................................................... 507
- .................................................................................................................. 509
QTextStream............................................................................................................... 509
QDataStream ............................................................................................................. 511
......................................................................................................................................... 511

38. , ............................................................................... 513


................................................................................................................................ 513
QDate ................................................................................................................ 513
QTime.......................................................................................................... 515
QDateTime...................................................................................... 516

XII

.......................................................................................................................................... 516
................................................................................................................. 517
QTimer ....................................................................................................................... 519
QBasicTimer .............................................................................................................. 521
......................................................................................................................................... 521

39. ................................................................................... 522


..................................................................................................................................... 522
.......................................................................................................................................... 525
......................................................................................................................... 527
........................................................................................................... 527
- .............................................................................. 528
...................................................................................................... 532
.................................................................................................................... 535
................................................................................................................... 536
................................................................................................................... 537
..................................................................................................... 538
........................................................................ 538
QtConcurrent............................................................................................................ 539
......................................................................................................................................... 541

40. ..................................................... 542


.................................................................................................................. 542
"-" ..................................................................................................... 543
TCP- ..................................................................................................... 544
TCP- .................................................................................................... 549
UDP- UDP- ................................................................................. 553
.......................................................................................................... 557
QFtp ........................................................................................................................... 557
QHttp.......................................................................................................................... 558
................................................................................................. 559
................................................................................................................. 566
.............................................................................................................................. 569
......................................................................................................................................... 569

41. XML ............................................................................................. 571


XML- ..................................................................... 571
XML Qt ..................................................................................................................................... 573
DOM .............................................................................................................................. 573
XML-...................................................................................................... 574
XML- .................................................................................. 576
SAX ............................................................................................................................... 578
XML-...................................................................................................... 578
QXmlStreamReader XML .............................................................................. 581
XQuery ............................................................................................................... 583
......................................................................................................................................... 586

42. ............................................................. 587


SQL ......................................................................................................... 587
............................................................................................................... 588
................................................................................................................ 588

XIII

..................................................................................................................... 588
.............................................................................................................. 589
.............................................................................................................................. 589
SQL Qt ............................................................................. 589
( ) ................................................................. 591
SQL ( ) ...................................................................... 592
SQL- ( ) .................................................... 595
.......................................................................................................... 596
...................................................................................................... 597
.................................................................................................. 599
......................................................................................................................................... 600

43. ............................ 601


......................................................................................................... 601
............................................................... 602
(plug-ins) ................................................................................................................. 605
Qt .............................................................................................................. 605
.................................................... 607
.................................................................... 610
......................................................................................................................................... 613

44. Qt API ......... 614


Windows API .............................................................................. 616
Linux ........................................................................................... 618
Mac OS X ................................................................................... 618
.............................................................................................................. 622
......................................................................................................................................... 623

45. Qt Designer. ..................................... 624


Qt Designer ....................................................................................... 624
................................................................................................................. 627
(layout) .................................................................................................................... 628
................................................................................................ 629
......................................................................................................................... 630
.................................................................... 632
............................................................................................... 632
................................................................................................................................. 634
.................................................................................................. 635
......................................................................................................................................... 637

46. .................................................................................... 639


.......................................................................................................................... 640
................................................................................................. 643
.............................................................................. 645
................................................................................................... 647
......................................................................................................................................... 647

47. WebKit ......................................................................................................... 648


.............................................................................................................. 649
? ....................................................................................................................................... 650

XIV

............................................................................................................................. 650
Web- ........................................................................................... 652
........................................................................................................................ 652
.......................................................................................................... 652
.............................................................................................. 653
Web-, ......................................................................... 653
......................................................................................................................................... 657

48. Qt Creator ................................. 658


............................................................................................................................. 659
"Hello Qt Creator" ............................................................................................ 659
Qt Creator................................................................................... 665
......................................................................................................................... 666
.......................................................................................... 666
.................................................................................... 666
............................................................................................................... 669
? .......................................................................................... 669
............................................................................................. 670
..................................................................................... 670
.................................................................................................................... 670
..................................................................... 675
............................................................................... 675
................................................................. 675
.......................................................................................... 675
................................ 676
, ................................................................................. 676
...................................................................... 677
............................................................. 677
..................................................................................................... 678
........................................................................................................... 679
............................................................................................ 680
............................................................................................................ 680
......................................................................................................................... 680
Step Over ...................................................................................................... 681
Step Into ....................................................................................................... 681
Step Out ........................................................................................................ 682
............................................................................................................. 682
(Local and Watches) .............................................................................. 683
(Call Stack) .................................................................................... 684
......................................................................................................................................... 684

49. Qt3 Qt4 .......................... 686


Qt4 Qt3 .................................................................................................... 686
..................................................................................... 687
......................................................................................................... 688
........................................................................................ 689
...................................................................... 689
Qt Designer ........................................................................................................................... 689

XV

Qt4 .............................................................................................................. 689


Qt3Support ................................................................................... 690
Qt4 .............................................................................................. 691
......................................................................................................................................... 692

VII. QT SCRIPT ..................................................... 693


50. ................................................................ 695
........................................................................ 696
....................................................................................... 699
, ........................................................................................................................ 700
......................................................................................................................................... 702

51. ................................................................... 703


......................................................................................... 703
............................................................................................................................... 704
................................................................................................................................. 704
....................................................................................... 705
................................................................................................................... 705
..................................................................................................... 705
........................................................................................................... 706
.......................................................................................................... 706
........................................................................................................ 706
.................................................................................................................................... 708
..................................................................................................................................... 708
................................................................................................... 708
................................................................................................. 708
....................................................................................................... 709
........................................................................................................... 710
...................................................................................... 711
........................................................................................................... 711
.......................................................................................................... 711
if ... else ....................................................................................................... 713
switch .......................................................................................................... 713
........................................................................................ 714
................................................................................................................................... 715
break continue....................................................................................... 715
for ....................................................................................................................... 715
while ................................................................................................................... 715
do...while ............................................................................................................ 716
with ...................................................................................................................... 716
................................................................................................ 716
try...catch .................................................................................................... 716
throw ........................................................................................................... 717
....................................................................................................................................... 717
.......................................................................................................... 719
................................................................................................................ 719
............................................................................................................ 722
....................................................................................................................... 722

XVI

............................................................................................................ 724
"" ....................................................................................................... 725
......................................................................................................................................... 726

52. Qt Script ............................................................... 727


Global .............................................................................................................................. 727
Number ............................................................................................................................ 727
Boolean............................................................................................................................ 727
String ............................................................................................................................... 728
............................................. 728
.................................................................................................................................. 728
........................................................................................................... 728
......................................................................................................... 728
RegExp ............................................................................................................................ 728
.................................................................................................................. 729
............................................................................................................... 729
Array................................................................................................................................ 729
...................................................................................... 730
.......................................................................................................... 730
............................................................................ 730
..................................................................................... 731
....................................................................................................... 731
................................................................................................ 731
....................................................................................................... 731
Date ................................................................................................................................. 732
th ................................................................................................................................ 733
....................................................................................................................... 733
.......................................................................................................................... 734
............................................................................... 734
.......................................................................................................... 734
......................................................................................... 734
............................................................................................... 735
............................................................................................. 735
.............................................................................. 735
Function .......................................................................................................................... 736
......................................................................................................................................... 736

53. Qt Script .................... 737


QScriptValue ...................................................................................................................... 737
QScriptContext ................................................................................................................... 737
QScriptEngine .................................................................................................................... 738
.............................................................................................................. 740
"" .......................................................................................................... 741
, ................................................................................................. 748
Qt Script ...................................................................................................................... 751
......................................................................................................................................... 754

VIII. QT QUICK.............................................................. 755


54. Qt Quick ............................................................................. 757
? ....................................................................................................................................... 757

XVII

QML.......................................................................................................................... 759
............................................................................................................................. 759
......................................................................................................................................... 763

55. .................................................................................................... 765


................................................................................................................. 765
.................................................................................................................... 767
........................................................................................................ 769
............................................................................................. 771
JavaScript QML .............................................................................................. 773
......................................................................................................................................... 774

56. ................................................... 775


................................................................................................................................... 775
........................................................................................................ 782
......................................................................................................................................... 784

57. ................................................................................... 785


............................................................................................................................................ 785
............................................................................................................. 786
Image ..................................................................................................................... 786
BorderImage .......................................................................................................... 789
.................................................................................................................................... 790
....................................................................................................................................... 791
......................................................................................................................................... 792

58. ........................................................................... 793


............................................................................................................................. 793
....................................................................................................................................... 796
...................................................................................................................... 800
.................................................................................................................................... 801
"" ....................................................................................................................... 803
......................................................................................................................................... 804

59. .................................................................................................... 805


............................................................................................. 805
.................................................................. 807
........................................................................................... 808
....................................................................................................... 809
.................................................................................................................. 810
......................................................................... 812
................................................................................................................ 815
............................................................................................................................ 815
............................................................................................................................. 818
......................................................................................................................................... 820

60. / ............................................................................ 822


......................................................................................................................................... 822
..................................................................................................................... 822
XML- ................................................................................................................................ 823

XVIII

................................................................................................ 825
Flickable ................................................................................................................ 825
ListView ................................................................................................................. 826
GridView ............................................................................................................... 828
PathView ............................................................................................................... 830
......................................................................................................................................... 833

61. Qt Quick C++ ........................................................................................... 834


QML C++ ............................................................................................. 834
C++ QML ...................................................................... 835
......................................................................................................................................... 838

........................................................................................................................... 839
.......................................................................................................... 841
1. ASCII ..................................... 843
2. ................................................................. 846
3. ......................................................................................... 849
4. ..................................................... 853
.............................................................................................. 863


,
,

(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 , !

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

1 2004,


,
. , (Ulrich
W. Eisenecker), .
: ,
, .

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



...

, Qt ( Qt),
.
, , .
, .
Qt Quick
QML.
. ,
.
,
, .
,
Qt. ,
. , Qt, , , , ,
, , ,
www.maxschlee.com.
, Qt ,
" " .
.


. ,
Qt, 49, Qt4 Qt3.

I. Qt
Qt.
1. Qt

1 , Qt, c , Qt.
2.

2 ,
, .
3. Qt

,
make-, .
4.

,
. . Qt ,
. " ",
. , , - .
, QString
, " ",
QVariant, .
II.

, . .
5.

5 .
, ,
, , , . ,
.
QStackedWidget,
.
6.

(Layouts), ,
QSplitter. .
7.

7 ,
.

, .
.
8. ,

8
: , .
.
.
9.

9 , ,
: , , .
10.

10 ,
.
: , ,
. QValidator .
11.

11 , , , , .
12. , -

- ,
.
13.

13 ,
.

III.
Qt.
14.

14 ,
, .
, , .
, .
15.

15 ,
. , QObject, , ,
, , . . -

,
.
16.

16 ,
, , .

IV.
, . .
17.

17 , , , . .
18.

, , , . ,
QPicture, , .
19.

19 QPixmap
QImage.
. ""
.
20.

.
21.

21 QGraphicsScene, . ,
, , .
22.

QMovie, GIF- MNG-.


23. OpenGL

23 OpenGL Qt, , . Qt, OpenGL. OpenGL: , , , .

10

24.

24 , :
,
.
25.

25 ,
. , , .
26.

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

27 , Qt .
28.

, Phonon.

V.
.
29.

29 . , , , , ,
.
30.


(drag & drop).
31.

. 31 , .
32.

. : , , ,
, ,
.

11

33.

33 .
, , . ,

.
34.

.
34 .
35. SDI- MDI-

,
QMainWindow. , SDI (Single Document Interface),
MDI (Multiple Document Interface).
36. (Desktop)

36
. ( Windows ) .
QSystemTrayIcon, .
, QDesktopWidget, .

VI. Qt
Qt, ,
, . . , , .
37. , -

37 , Qt ,
.
, ().
38. ,

, ,
.
39.

39 ,
, . -

12

, .
(mutex) , , .
40.

40 , TCP/UDP-,
. : QFtp, FTP; QHttp,
HTTP; QNetworkAccessManager.
41. XML

, XML (eXtensible Markup Language).


XML-. DOM (Document Object Model) , DOM- XML-.
SAX (Simple API for XML) XML-.
42.

42 . . QSqlQuery
SQL- (Structured Query Language), , .
"".
43.

,
. . , (plugins).
44. Qt API

44 Windows Linux , Qt.


45. Qt Designer.

45, Qt Designer,
, .
46.

. 46
, Qt .
47. WebKit

47 QtWebKit, WWW (World Wide Web)


Web. , Web-
Web-.

13

48. Qt Creator

48 , ,
. , .
49. Qt3 Qt4

Qt ,
, Qt3, Qt4,
. 49 , Qt4, ,
Qt4. , , .

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

Qt Script Qt , .
51.

51 :
, , , ,
, .
52. Qt Script

Qt Script . Object, Math, String,


Boolean, RegExp, Number, Date . .
53. Qt Script

53 ,
C++ , , .

VIII. Qt Quick
Qt Quick,
QML .
54. Qt Quick

, Qt Quick, , . , Qt Quick.

14

55.

,
.
56.

56 Qt
(layout) ,
QML. ,
.
57.

, , .
58.

58 ,
, .
59.

, , , . .
, , .
60. /

60 , .
61. Qt Quick C++

, C++,
QML ( Qt Quick) .

. 1 ASCII-,
2 , 3 , 4 .

, . Software GUI (Graphical User Interface)


.
(), Motif UNIX
MFC (Microsoft Foundation Classes) Microsoft Windows.
Windows API (Application Programming Interface, ) , "" . MFC, Windows, ,
. - . ,
.
Windows, , ,
- ? ,
.
.
. , UNIX, , Windows. ,
(). : , . .
, , , .
,
, . , , XCode-Instruments Mac OS X, .
, . .
,
.

16

Qt , C++,
Windows, Linux
Mac OS X. Qt . Qt
: Microsoft Windows (Windows XP/Vista/Windows 7),
Mac OS X, Linux, Solaris, AIX, Irix, NetBSD, OpenBSD, HP-UX, FreeBSD
UNIX X11. , Qt Embedded
Qt (Embedded Systems). Qt API , ,
, . , 1 Qt
MeeGo, WebOS, iPhone Android.
,
, Qt , . , .
. , - .
C++
, .
Qt Qt Designer, .
Qt , .
, , 4000. Qt , : Adobe, AT&T, Cannon, HP,
Bosch, Boeing, IBM, Motorola, NASA, NEC, Pioneer, Sharp, Siemens, Sony Xerox .
, , , ,
Qt. , ,
:
KDE Software Compilation 4 (www.kde.org), Linux

FreeBSD (. .1);
Autodesk Maya (www.autodesk.com) (. .2);
- Skype (www.skype.com) Microsoft,

VoIP (Voice Over IP), (. .3);


Adobe Photoshop Album (www.adobe.com) -

(. .4);
Google Earth (earth.google.com),

200 (. .5);
1

(. porting) , , ,
. .

17

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

. .2. 3D- Autodesk Maya ( www.wikipedia.org)

18

. .3. Skype

. .4. Adobe Photoshop Album

19

. .5. Google Earth

VirtualBox (www.virtualbox.org)

Sun Microsystems (. .6);


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

0.9 (. .7);
Parallels (www.parallels.com)

Parallels (. .8).
Qt, .
Qt-, , :
TraderStar (www.neonway.com/traderstar),

(. .9);
HappyBirthday (www.neonway.com/happy), -

, (. .10);

FLEXXITY (www.dft-film.com/archive/flexxity_archive.php), ,
(. .11).

, Qt . , Qt .
:
- (, -

OpenGL);

20

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

. .7. VLC media player

21

. .8. Parallels

. .9. TraderStar

22

. .10. HappyBirthday

. .11. FLEXXITY

23

;
XML (eXtensible Markup Language);
STL- ;
-;
;
, Oracle, Microsoft SQL

Server, IBM DB2, MySQL, SQLite, Sybase, PostgreSQL;


.
Qt - . , " ", ,
. , , . .
(plug-ins) ,
.
, .
, Qt
C++, , . ,
,
Qt Jambi Java, Qt# C#, PerlQt Perl, PyQt Python, PHP . .
, Qt, Qt Script.

, "" .
Qt , , Qt Asisstant.
, , Qt (Open Source),
, .
, Qt :
+ + .
Qt!

4 2012 .

24

Qt
, ,
, .

1.

Qt

2.

3.

Qt

4.

Qt

.

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

. , .
, . , , .
. 1.1.
"Hello World"

1.1. "Hello World". hello.cpp

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

1.1 QtGui, ,
: QApplication QLabel. ,

28

I. Qt

QtGui,
QApplication QLabel, , -

, . , (Precompiled Headers) ,
.
. QApplication, .
. ,
, , , . Qt-
, , .
QLabel. Qt , show().
QLabel ,
. ,
,
.
,
.
,
QApplication::exec(). , QCoreApplication, QApplication.
.
,
QCoreApplication::exit(), .
QApplication::exec()
, , .

Qt
-
. Qt ,
, .
Qt ( 500),
,
, , , .
. Qt , (. 1.1).
Qt- , QtCore QtGui, make- (. 3) .
(. 3). ,
,
QT += opengl network sql

1. Qt

29
1.1. Qt

QtCore

core

, ,

QtGui

gui

QtNetwork

network

QtOpenGL

opengl

OpenGL

QtSql

sql

QtSvg

svg

SVG (Scalable Vector Graphics,


)

QtXml

xml

XML, , SAX
DOM

Qt3Support

qt3support

,
Qt

QtScript

script

Phonon

phonon

QtWebKit

webkit

Web-

QtScriptTools

scripttools

QtTest

test

. 1.2.

I. Qt

30

:
QT -= gui

. 1.1 QtCore, . .
(. 1.2). , QtCore, QtNetwork, QtGui, QtSql QtXml. , , , Qt3Support, QtOpenGL QtSvg.
Qt , . . , QtGui

#include <QtGui>

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

QtCore
, QtCore. , .
, , , . QtCore 200 ,
:
QList, QVector, QMap (. 4);
QIODevice, QTextStream, QFile (. 37);

QProcess
QWaitCondition, QMutex (. 39);

QThread,

QBasicTimer QTimer (. 38);


QDate QTime (. 38);
QObject, Qt (. 2);
QEvent (. 14);
QSettings (. 29);
QCoreApplication, , , -

.
QCoreApplication.
QCoreApplication , , . QCoreApplication ,

1. Qt

31

. QCoreApplication . :
;
.

, QCoreApplication ,
, , . Singleton.

QtGui
,
. 300 . :
QWidget Qt.

, ,
. 254 53 . 5
;
QVBoxLayout, QHBoxLayout (. 6);
QLabel, QLCDNumber (. 7);
QPushButton, QCheckBox, QRadioButton (. 8);
QSlider, QScrollBar (. 9);
QLineEdit, QSpinBox (. 10);
QComboBox, QToolBox (. 11);
QMainWindow QMenu (. 32 35);
QMessageBox, QDialog (. 33);
QPainter, QBrush, QPen, QColor (. 18);
QImage, QPixmap (. 19);
QMotifStyle, QWindowsStyle . (. 26). ,

,
;
QApplication, .

, QApplication,
. ,
QCoreApplication, , . . . QApplication
Qt-, .
, , , . ,
, .

I. Qt

32

QApplication :
. Motif,
Windows, (Look & Feel) ,

(c. 26);
(desktop);
(c. 30);
(,

) ;
(c. 27);

(. 29);
,

(. 13).
, ,
. QApplication
alert(). -
Mac OS X, Windows ,
. 1.3 1.4.

. 1.3.
- Mac OS X

. 1.4.
Windows 7

QtNetwork
TCP- UDP-
( QTcpSocket QUdpSocket), -, HTTP- FTP- ( QHttp QFtp). 40.

QtXml
XML SAX2- DOM-,
Qt (. 41).

1. Qt

33

QtSql
. , (. 42).

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

QtWebKit
Web. Web .
47.

QtSvg
SVG, XML.
, (. 22).

Qt3Support
Qt , , . , ,
.
Qt- Qt4. ,
, Qt4.
Qt- Qt4 49.

Qt , :
QtCore, QtGui, QtNetwork, QtOpenGL, QtSql, QtXml QtSvg.
, , ,
. ,
, , .
QtCore,
( ).
QCoreApplication .

QtGui. QApplication Qt- .
. , .


,
, , .

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

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

class MyClass : public QObject, public AnotherClass {


...
};


, QObject
. ,
, QObject.

QObject :
(signal/slot);
;
;
;
;
;

2.

35

;
.

, , .
.
,
QObject, . . 38.

, , . . - .
.
, QObject,
(. 15).
, , ,
.
Qt qobject_cast<T>(), , MOC
(. 3), , QObject.
, .
, Qt Script (. VII). Qt Designer (. 45). 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).

I. Qt

36
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->setProperty("readOnly", true);

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


. .
(callback functions),
X Window System, , .

2.

37

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

class CPhotoStylerApp : public CWinApp {


public:
CPhotoStylerApp();
public:
virtual BOOL InitInstance();
afx_msg void OnAppAbout();
afx_msg void OnFileNew();
DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(CPhotoStylerApp, CWinApp)
ON_COMMAND(ID_APP_ABOUT, OnAppAbout)
ON_COMMAND(ID_FILE_NEW, OnFileNew)
ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew)

38

I. Qt

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++. , ++ ,
, .
, ,
. , Qt
" ". , Qt C++ .
C++ Qt
MOC (Meta Object Compiler, ). Q_OBJECT
. , .
C++, , . MOC, , . Q_OBJECT
class .
, . , .
, -. Qt,

2.

39

. QObject
. . : , .
: ""
"", "" " ".
:
, QObject,

;
, , -

;
. -

;
, -

;
;
, .

, , (. 39);
-

. , .
, :
C++, -

;
, , -

;
QObject;
:

;
. , . , ,
Windows, (. 3)
CONFIG console ( Linux ).

(signals) : , , , . .
Qt ,
.
, . ,
, , . -

40

I. Qt

,
. , ,
, . , , ,
. , , ,
.
; ,
, ,
, .
.
Qt -
. , ,
.
, , .
, . MOC. - ,
void.
. ,
.
, -
, .

. , , . 2.4.
2.4.

class MySignal {
Q_OBJECT
...
signals:
void doIt();
...
};

doIt(). , MOC, :
void MySignal::doIt()
{
QMetaObject::activate(this, &staticMetaObject, 0, 0);
}

, private,
protected public, . . .

2.

41

emit. ,
, emit doIt() doIt(). , .
, 2.4 doIt()
MySignal, .
, sendSignal(),
MySignal doIt(), 2.5.
2.5.

class MySignal {
Q_OBJECT
public:
void sendSignal()
{
emit doIt();
}
signals:
void doIt();
};

, .
, , , 2.6.
2.6.

class MySignal : public QObject {


Q_OBJECT
public:
void sendSignal()
{
emit sendString("Information");
}
signals:
void sendString(const QString&);
};

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

Nokia,
, . ,
.

I. Qt

42

, , .
, slotMethod(int n = 8), static.
.
. 2.7.
2.7.

class MySlot : public QObject {


Q_OBJECT
public:
MySlot();
public slots:
void slot()
{
qDebug() << "Im a slot";
}
};

sender() , . QObject. ,
, :
void slot()
{
qDebug() << sender()->objectName();
}


connect(),
QObject. , connect()
:
QObject::connect(const QObject*
const char*
const QObject*
const char*
Qt::ConnectionType
);

sender,
signal,
receiver,
slot,
type = Qt::AutoConnection

:
sender , ;
signal , . ( -

) SIGNAL(method());
receiver , ;
slot , .

SLOT(method());
type

Qt::DirectConnection -

2.

43

, Qt::QueuedConnection (. 14) , Qt::AutoConnection , : ,


Qt::DirectConnection, Qt::QueuedConnection.
(Qt::AutoConnection) connection() . "", , .
,
.
void main()
{
...
QObject::connect(pSender, SIGNAL(signalMethod()),
pReceiver, SLOT(slotMethod())
);
...
}

, 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()
{
qDebug() << "Im a slot";
}

, ,
. ,
( emit) .
. :
MyClass::MyClass() : QObject()
{
connect(pSender, SIGNAL(signalMethod()), SIGNAL(mySignal()));
}

I. Qt

44

, blockSignals()
true. "", blockSignals() false.
signalsBlocked() .
, . 2.1,
. ( 2.82.10),
, . ADD ()
1.
, .

. 2.1. -.

2.8. main.cpp

#include <QtGui>
#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()),
&counter, SLOT(slotInc())
);
QObject::connect(&counter, SIGNAL(counterChanged(int)),
&lbl, SLOT(setNum(int))
);
QObject::connect(&counter, SIGNAL(goodbye()),
&app, SLOT(quit())
);
return app.exec();
}

2.

45

( 2.8) lbl, cmd counter ( 2.92.10). clicked() slotInc(). slotInc(), 1.


, . counterChanged(int), , setNum(int),
.

, , . , , int, , QString.

, goodbye(), , quit(), ,
ADD . ,
.
2.9. Counter.h

#ifndef _Counter_h_
#define _Counter_h_
#include <QObject>
// ======================================================================
class Counter : public QObject {
Q_OBJECT
private:
int m_nValue;
public:
Counter();
public slots:
void slotInc();
signals:
void goodbye
(
);
void counterChanged(int);
};
#endif //_Counter_h_

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

I. Qt

46
2.10. ounter.cpp

#include "Counter.h"
// ---------------------------------------------------------------------Counter::Counter() : QObject()
, m_nValue(0)
{
}
// ---------------------------------------------------------------------void Counter::slotInc()
{
emit counterChanged(++m_nValue);
if (m_nValue == 5) {
emit goodbye();
}
}

2.10 slotInc() : counterChanged()


goodbye(). goodbye() m_nValue, 5.
, , , .
, , , . :
MyClass::MyClass() : QObject()
{
connect(pSender, SIGNAL(signalMethod(int)), SIGNAL(mySignal()));
}

, ,
. , , .


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

,
:
void main()
{
...

2.

47

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

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


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

QObject
. . -.
, , ,
. - ,
setParent().
. setObjectName()
. , . ,
objectName().
2.11.

QObject* pobj1 = new QObject;


QObject* pobj2 = new QObject(pobj1);
QObject* pobj4 = new QObject(pobj2);
QObject* pobj3 = new QObject(pobj1);
pobj2->setObjectName("the first child of pobj1");
pobj3->setObjectName("the second child of pobj1");
pobj4->setObjectName("the first child of pobj2");

2.11 ( ).
pobj2 , , pobj1. pobj3 pobj1, pobj4 pobj2.
. 2.2.
( )
- .
, . .
. , , , new, .

I. Qt

48

. 2.2.


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

: parent()
children(). parent() -.
. 2.2, pobj2->parent() obj1.
0. - , , 2.12 ( pobj4 2.11).
2.12.

for (QObject* pobj = pobj4; pobj; pobj = pobj->parent()) {


qDebug() << pobj->objectName();
}

:
the first child of pobj2
the first child of pobj1

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

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

2.

49

qFindChildren(),
:
QList<QObject*> plist = ::qFindChildren<QObject*>(pobj1);

pobj2, pobj3
pobj4.
dumpObjectInfo(),
, :
;
, ;
- .

stdout.
dumpObjectTree(),
- . , dumpObjectTree()
pobj1 2.11 :
QObject::
QObject::the first child of pobj1
QObject::the first child of pobj2
QObject::the second child of pobj1


, QObject , , (
QMetaObject). , ( ),
.
QObject::metaObject(). , , , , , :
qDebug() << pobj1->metaObject()->className();

, :
if (pobj1->metaObject()->className() == "MyClass") {
// -
}

inherits(const
char*), QObject true,

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

qobject_cast<T>.
, inherits() :

50

I. Qt

QWidget* pwgt = qobject_cast<QWidget*>(pobj);


if(pwgt) {
// - pwgt
}

tr(), . 31.

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

signals, slots. C++
public, protected, private. MOC.
emit. , ,
QObject , . - (), disconnect(),
, . .
.
QObject::connect().
QObject , Qt. QObjet :

, . , . . . QObject
new,
.
, C++, ,
MOC ( ), cpp-,
. MOC
, ,
Q_OBJECT.

Qt
, .

, , Qt.

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

Qt Assistant
, . Qt
1500 HTML- , . Qt Assistant, Web-. Qt Assistant
Qt. , -docPath. . 3.2
Qt Assistant.
QAssistantClient Qt Assistant
.

qmake
"".
make- (makefile), .

I. Qt

52

. 3.1. Qt Creator

. 3.2. Qt Assistant

3. Qt

53

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

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

, file.pro pro-, Makefile make-.



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

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

, pro-,
. 3.1
pro-, Qt, (
Qt Assistant).
3.1.

HEADERS

SOURCES

( cpp)

I. Qt

54

3.1 ()

FORMS

ui.
Qt Designer XML
(. 41 45)

TARGET

. ,

LIBS

CONFIG

DESTDIR

DEFINES

. ,
debuger

INCLUDEPATH

, .
,
()

DEPENDPATH

SUBDIRS

, pro-

TEMPLATE

. : app , lib , subdirs

TRANSLATIONS

, (. 31)

"" . , pro-
:
TEMPLATE = app
HEADERS += file1.h \
file2.h
SOURCES += main.cpp \
file1.cpp \
file2.cpp
TARGET = file
CONFIG += qt warn_on release

. ,
TEMPLATE = app ( , TEMPLATE
lib). , HEADERS,
, . SOURCES . TARGET , CONFIG , . ,
:
qt , Qt- Qt;
warn_on , -

;
release ,

, .

3. Qt

55


Mac OS X CONFIG ,
. , 32- Intel- x86, 64- Intel- x86_64. 32- PowerPC ppc, 64- ppc64.
, , , .
CONFIG,
Intel PowerPC: CONFIG += debug x86 ppc x86_64 ppc64.
Universal Binaries,
Mac OS X.

, qmake , . . , .
, qmake make- , .

.
, . pro- ,
FTP- ftp://85.249.45.166/9785977507363.zip. :
TEMPLATE = subdirs
SUBDIRS = Example1 Example2 .... ExampleN


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

!

ftp://85.249.45.166/9785977507363.zip, , "-" www.bhv.ru.

Qt
. h,
cpp. , #ifndef.
, ,
.
#ifndef _MyClass_h_
#define _MyClass_h_
class MyClass {
...
};
#endif //_MyClass_h_

I. Qt

56

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

, " " . main.cpp.


, , ,
.
.
,
, ,
Qt , " ".

MOC
(MOC, Meta Object Compiler), , , , , , , C++.
- ,
. - ,
C++.
moc_<filename>.cpp.
!
moc- #include
"main.moc" . :
#include <QtGui>
int main(int argc, char** argv)
{
QApplication app(argc, argv);
...
return app.exec();
}
#include "main.moc"
, .
, main.cpp.

3. Qt

57

, MOC ,
MOC . moc- ""
:
moc o proc.moc proc.h

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

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

rcc,
open.png quit.png C++,
,
. C++ .
, , . qrc- pro- RESOURCES,
qmake . :
RESOURCES = images.qrc

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

Qt-
Qt- .
, , . Qt , -

I. Qt

58

C++ pro.
qmake make-. make-
(. 3.3).

. 3.3.

make- MOC C++ . qrc-,


C++, .
C++- , link
.


(bug, ).
. , . , , :
(code review);
, 46.

, , , ,
, , -

3. Qt

59

, . , , ,
, . Qt
,
GDB , Microsoft Visual Studio.
, ,

, . GDB, Windows, Linux Mac OS X.

GDB MinGW (Windows) -,
, . 3.

GDB (GNU Debugger)


GDB OC Unix. , , , : XXGDB, DDD KDBG. ,
IDE,
" ". IDE, GDB .
, , .
3.1.

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

3.1 main() bug(), n, pn


delete , n.
,
.

I. Qt

60

-g,
, :
g++ -g bug.cpp o 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

, . , .
where:
(gdb) where

:
#0
...
#6
#7
#8

0x77f767ce in _libmsvcrt_a_iname ()
0x00401305 in operator delete(void*) ()
0x004012ae in bug() () at bug.cpp:5
0x004012df in main () at bug.cpp:10

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

:
#7
5

0x004012ae in bug() () at bug.cpp:5


delete pn;

3. Qt

61

- ,
print. n:
(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.2. GDB

quit

help

. ,

run

attach

detach

break

. . , . , < >:< > < >:< >

tbreak

break ,

clear

.
.
, . ,
: < >:< >
< >:< >

delete

disable

I. Qt

62

3.2 ()

enable

continue

next

step

. . next,

until


, .
, -. Qt
QObject::dumpObjectInfo(), .
Qt ,
.
QtGlobal Q_ASSERT()
Q_CHECK_PTR():
Q_ASSERT() -

, true;
Q_CHECK_PTR() , -

0, , ,
.
Qt qDebug(), qWarning() qFatal(), QtGlobal. printf().
printf(), . Microsoft Visual Studio ,
Linux .

qFatal() .

,
.
qInstallMsgHandler().
, :
void fct(QtMsgType type, const char *msg);

3. Qt

63

fct . , QtMsgType: QtDebugMsg, QtWarningMsg


QtFatalMsg. .
.
, , QObject::objectName().
QObject::
dumpObjectInfo(), .

QCoreApplication, ,
(. 15).
Qt QDebug.
C++ cout. ,
qDebug() :
qDebug() << "Test";

QDebug,
QtDebugMsg. , , :
QDebug(QtDebugMsg) << "Test";

, , ,
.
, qDebug()
.
, ,
:
#if defined(QT_DEBUG)
#define QDEBUG(X) qDebug() << X;
#else
#define QDEBUG(X) ;
#endif

qDebug() :
QDEBUG("Test1" << 123 << "Test2" << 456);

, , ,
, , ,
.

Qt
Qt QtGlobal ,
.
qMax(a, b) qMin(a, b) .
int n = qMax<int>(3, 5); // n = 5
int n = qMin<int>(3, 5); // n = 3

I. Qt

64

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

qRound() :
int n = qRound(5.2); // n = 5
int n = qRound(-5.2); // n = -5

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

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


, 46.

. 3.3 Qt, .
3.3. Qt
Qt

C++

qint8

signed char

quint8

unsigned char

qint16

short

16

quint16

unsigned short

16

qint32

Int

32

quint32

unsigned int

32

qint64

__int64 long long

64

quint64

unsigned __int64 unsigned long long

64

qlonglong

, qint64

64

qulonglong

, quint64

64

3. Qt

65

. 3.3, qint64 quint64, ,


:
qDebug()
qDebug()
qDebug()
qDebug()
qDebug()
qDebug()

<<
<<
<<
<<
<<
<<

"Number of bits for qint64 ="


"Minimum of qint64 = -"
"Maximum of qint64 ="
"Number of bits for quint64 ="
"Minimum of quint64 ="
"Maximum of quint64 ="

<<
<<
<<
<<
<<
<<

(sizeof(qint64) * 8);
~(~quint64(0) >> 1);
(~quint64(0) >> 1);
(sizeof(quint64) * 8);
0;
~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.2).
3.2. QLibraryInfo

#include <QtCore>
int main(int argc, char** argv)
{
qDebug() << "Build date:"
<< QLibraryInfo::buildDate().toString("yyyy-MM-dd");
qDebug() << "Build key:"
<< QLibraryInfo::buildKey();
qDebug() << "License Products:"
<< QLibraryInfo::licensedProducts();
qDebug() << "Licensee:"
<< QLibraryInfo::licensee();
qDebug() << "Locations";
qDebug() << " Headers:"
<< QLibraryInfo::location(QLibraryInfo::HeadersPath);
qDebug() << " Libraries:"
<< QLibraryInfo::location(QLibraryInfo::LibrariesPath);
qDebug() << " Binaries:"
<< QLibraryInfo::location(QLibraryInfo::BinariesPath);

I. Qt

66
qDebug() <<
<<
qDebug() <<
<<
qDebug() <<
<<
qDebug() <<
<<
qDebug() <<
<<
qDebug() <<
<<
qDebug() <<
<<

" Prefix"
QLibraryInfo::location(QLibraryInfo::PrefixPath);
" Documentation: "
QLibraryInfo::location(QLibraryInfo::DocumentationPath);
" Plugins:"
QLibraryInfo::location(QLibraryInfo::PluginsPath);
" Data:"
QLibraryInfo::location(QLibraryInfo::DataPath);
" Settings:"
QLibraryInfo::location(QLibraryInfo::SettingsPath);
" Demos:"
QLibraryInfo::location(QLibraryInfo::DemosPath);
" Examples:"
QLibraryInfo::location(QLibraryInfo::ExamplesPath);

Qt4.7.1, Windows.
Build date: "2010-11-22"
Build key: "Windows mingw debug full-config"
License Products: "OpenSource"
Licensee: "Open Source"
Locations
Headers: "C:/Qt/4.7.1/include"
Libraries: "C:/Qt/4.7.1/lib"
Binaries: "C:/Qt/4.7.1/bin"
Prefix "C:\Qt\4.7.1"
Documentation: "C:/Qt/4.7.1/doc"
Plugins: "C:/Qt/4.7.1/plugins"
Data: "C:/Qt/4.7.1"
Settings: "C:/Qt/4.7.1"
Demos: "C:/Qt/4.7.1/demos"
Examples: "C:/Qt/4.7.1/examples"

, Qt
" " .
qmake,
make- . MOC,
, Qt-, , . Qt
Qt- GDB.


, ?
" "


.
, . .
. ,
.
.
Qt , Tulip,
Qt, .
STL (Standard Template Library, ), . , , Tulip STL. , . . Tulip Qt . Tulip ,
Qt . , ,
, .
, , , , . Tulip , ,
.
Tulip QtCore. Tulip (
STL) :
();
;
.

. 4.1.

I. Qt

68

. 4.1. ,


, . Qt ,
, .
, . , , ,
.
,
.
. Qt
: (sequence containers)
(associative containters).
, . .
: (vector), (list), (stack) (queue). , Qt :
QVector<T> ;
QList<T> ;
QLinkedList<T> ;
QStack<T> ;
QQueue<T> .

,
, . . . : (set),
(map) (hash). :
QSet<T> ;
QMap<K,T> ;

4.

69

QMultiMap<K,T> ;
QHash<K,T> ;
QMultiHash<K,T> .

, . 4.1. , , QSet<T>.
4.1. ,
,

== !=

[]

.
QSet<T> QLinkedList<T>,

begin() constBegin()

, ,
. QSet<T>

end() constEnd()

, ,

clear()

insert()

remove()

size() count()


, , . . STL

value()

. QSet<T>

empty() isEmpty()

true, . , , . . STL


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

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

I. Qt

70

. . , . ., - ,
, , ,
. , , .
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.
QLinkedListIterator, QVectorIterator, QHashIterator, QMapIterator. , , ,
.
4.2. QListIterator

toFront()

toBack()

hasNext()

true,

next()

peekNext()

4.

71
4.2 ()

hasPrevious()

true,

previous()

peekPrevious()

findNext(const T&)

findPrevious(const& T)

,
(mutable) .
, "Mutable": QMutableListIterator,
QMutableHashIterator, QMutableLinkedListIterator, QMutableMapIterator QmutableVectorIterator. remove() , insert() . setValue()
. "Boney M" "Rolling Stones":
QList<QString> list;
list << "Beatles" << "ABBA" << "Boney M";
QMutableListIterator<QString> it(list);
while(it.hasNext()) {
if (it.next() == "Boney M") {
it.setValue("Rolling Stones");
}
qDebug() << it.peekPrevious();
}

Java , , , , STL, .

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

I. Qt

72
QVector<QString> vec;
vec << "In Extremo" << "Blackmore's Night" << "Cultus Ferox";
QVector<QString>::iterator it = vec.begin();
for (; it != vec.end(); ++it) {
qDebug() << "Element:" << *it;
}

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

, it , . . ++it. , ,
, , .

. 4.2. begin(), end()

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

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

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

, STL, algorithm. ,
STL- sort() :

4.

73

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

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

Qt , .

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

foreach, , break, continue,


.
!
Qt foreach,
, .


,
. , , . 4.3.
4.3.
/

+=

( , <<)

<<

at()

back() last()

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

contains()

I. Qt

74

4.3 ()
/

erase()

, ,

front() first()

.
, . front()
first() , , . . STL

indexOf()

, .
: QLinkedList

lastIndexOf()

, . : 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");
qDebug() << vec;

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

QVector<T>
, (. 4.3). , ,
. , , .
!
push_front(), prepend(), pop_front() remove(),
. .

4.

75

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

. 4.3.

(. . 4.3)
push_back(). [] (. . 4.1), . :
QVector<int> vec;
vec.push_back(10);
vec.push_back(20);
vec.push_back(30);
qDebug() << 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[1] = 0xFF;
arr[2] = 0x0;

76

I. Qt

QByteArray
. : qCompress()
qUncompress(). :
QByteArray a
= "Test Data";
QByteArray aCompressed = qCompress(a);
qDebug() << qUncompress(aCompressed);

"Test Data".
, . , XML- (. 41). QByteArray
: toBase64() fromBase64().
, Base64.
. , , :
QByteArray a
= "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[1] = true;
bits[2] = false;

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

4.

77

!

size(), . . ,
. , ,
, empty() isEmpty().

QList<T>.
(. 4.4).

. 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.end()) {
qDebug() << "Element:" << *it;
++it;
}

I. Qt

78

:
Element:10
Element:20
Element:30

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()) {
qDebug() << "Element:" << stk.pop();
}

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

. 4.6.

4.

79

QQueue<T>
, FIFO (First In First Out,
), . .
, , (. 4.7). QQueue<T>, QList<T>.
:
QQueue<QString> que;
que.enqueue("Era");
que.enqueue("Corvus Corax");
que.enqueue("Gathering");
while (!que.empty()) {
qDebug() << "Element:" <<que.dequeue();
}

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

. 4.7.


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

contains()

true,
. false

erase()

find()

. , ,
end()

insertMulti()

. , .
QSet<T>

insert()

. , .
QSet<T>

key()

. QSet<T>

keys()

, .
QSet<T>

I. Qt

80

4.6 ()

take()

. QSet<T>

unite()

values()

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

. 4.8.

. 4.9.

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

[]. , . .
key() value(), :

4.
QMap<QString, QString>
mapPhonebook["Piggy"]
mapPhonebook["Kermit"]
mapPhonebook["Gonzo"]

81

mapPhonebook;
= "+49 631322187";
= "+49 631322181";
= "+49 631322186";

QMap<QString, QString>::iterator it = mapPhonebook.begin();


for (;it != mapPhonebook.end(); ++it) {
qDebug() << "Name:" << it.key()
<< " Phone:" << it.value();
}

:
Name:Gonzo Phone:+49 631322186
Name:Kermit Phone:+49 631322181
Name:Piggy Phone:+49 631322187
4.7. QMap<K,T>

lowerBound()

toStdMap()

STL ,
QMap<T>

upperBound()

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

, , , .
QMap<K,T> . QMultiMap<K,T>. . 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");

I. Qt

82
for (; it != mapPhonebook.end() && it.key() == "Piggy"; ++it) {
qDebug() << it.value() ;
}

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

qHash() ,
. :
inline uint qHash(const MyClass& mc)
{
return qHash(mc.firstName()) ^ qHash(mc.secondName());
}

QMultiHash<K,T> QHash<K,T>. , , QMultiMap<K,T>,


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

capacity()

reserve()

squeeze()

QSet<T>
, " ,
". "", Tulip, ,
QSet<T>,

4.

83

, , , . , . QSet<T> - QHash<K,T>, , . .
.
. QSet<T>
. . 4.10,
, .
, , . 4.11.

. 4.10.

. 4.11.

. 4.10.
QSet<QString> set1;
QSet<QString> set2;
set1 << "Therion" << "Nightwish" << "Xandria";
set2 << "Mantus" << "Hagard" << "Therion";

(. . 4.11, ) ,
,
setResult:
QSet<QString> setResult = set1;
setResult.unite(set2);
qDebug() << " = " << setResult.toList();

:
= ("Xandria", "Hagard", "Mantus", "Nightwish", "Therion")

(. . 4.11, ):
setResult = set1;
setResult.intersect(set2);
qDebug() << " set1 c set2 = " << setResult.toList();

,
:
set1 c set2 =

("Therion")

I. Qt

84

, ,
(. . 4.11, ):
setResult = set1;
setResult.subtract(set2);
qDebug() << " set1 c set2 = " << setResult.toList();

set1 set2 , :
set1 c set2 =

("Xandria", "Nightwish")

. 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.

85
4.10.

qBinaryFind()

qCopy()

qCopyBackward()

qCount()

qDeleteAll()

. ,

qEqual()

. , ==

qFill()

qFind()

qLowerBound()

qUpperBound()

qSort()

qStableSort()

qSwap()

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

:
Sorted list=("Anubis", "Mantus", "Within Temptation")

- qFind() (. . 4.10). , end(),


.
QList<QString> list;
list << "Within Temptation" << "Anubis" << "Mantus";
QList<QString>::iterator it =
qFind(list.begin(), list.end(), "Anubis");

86

I. Qt

if (it != list.end()) {
qDebug() << "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[1] = "Anubis";
vec[2] = "Mantus";
qDebug() << "Equal="
<< qEqual(list.begin(), list.end(), vec.begin());

:
Equal=true

- , "Mantus"
"Mantux", qEqual() false.


-
. qFill() (. . 4.10).
"Beatles":
QList<QString> list;
list << "Within Temptation" << "Anubis" << "Mantus";
qFill(list.begin(), list.end(), "Beatles");
qDebug() << list;

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

. Qt
QString, , Unicode, -

4.

87

. QVector,
,
QChar, . ., , . QString
,
, , , .
==, !=, <, >, <=
>=. , :
QString str = "Lo";
bool b1 = (str == "Lo"); // b1 = true
bool b2 = (str != "LO"); // b2 = true

isEmpty() , .
, length(). QString
, , , , . :
QString str1 = "";
QString str2;
str1.isNull(); // false
str2.isNull(); // true

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

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


toLower() toUpper(). :
QString str1 = "LoStRiS";
QString str2 = str1.toLower(); // str2 = "lostris"
QString str3 = str1.toUpper(); // str3 = "LOSTRIS"

setNum() .
number(). :
QString str = QString::number(35.123);

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

I. Qt

88

,
.
, . :
bool ok;
QString str = "234";
double d
= str.toDouble(&ok);
int
n
= str.toInt(&ok);

split()
QStringList. : "Ringo" "Star":
QString str = "Ringo Star";
QStringList list = str.split(" ");


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


Qt QRegExp. . ,
.
. , , QString, . 4.11 , QRegExp.
4.11.

a.b

Abc$

[]

[abc]

[]

[0-9A-Za-z]

[^def]

A*b

A+b

A?b

{n}

A{3}b

{n,}

a{3,}b

{,n}

a{,3}b

4.

89
4.11 ()

{n,m}

n m

a{2,3}b

ac|bc

\b

a\b

\B

a\Bd

(ab|ac)ad

\d

\D

\s

\S

\w

\W

\A

\b

\B

\Z

(
)

\z

( )

,
. [ab] a b. ,
, [A-Z] ,
[a-z] , [0-9] .
, , [a-z7]
7.
, ^. [^0-9] , .
. 4.11 . , . , a{4,5} , a 4,
5 . ,
ip-, , , , ip-:
QRegExp reg("[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}");
QString str("this is an ip-address 123.222.63.1 lets check it");
qDebug() << (str.contains(reg) > 0); // true

,
(\), ++
. , . 4.11 " ", , , "1z2y3x4", ip-, , , .

I. Qt

90

|,
. ,
. :
QRegExp rxp("(.com|.ru)");
int n1 = rxp.indexIn("www.bhv.ru"); // n1 = 7 ( 7- )
int n2 = rxp.indexIn("www.bhv.de"); // n2 = -1 ( )

. 4.11 ( )
. , [a-zA-Z09_] \w.

QVariant
QVariant , .
: int, unsigned int, double, bool, QString, QStringList, QImage,
QPixmap, QBrush, QColor, QRegExp . , , . QVariant .
QVariant
. :
QVariant v1(34);
QVariant v2(true);
QVariant v2("Lostris");

type() QVariant . . ,
typeToName(). typeName(), :
QVariant v(5.0);
qDebug() << QVariant::typeToName(v.type()); // =>double

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


, QVariant QtCore, toT() QColor, QImage QPixmap ., QtGui, .

toT() value<T>(). QVariant


:
QVariant v2(23);
int a = v2.value<int>() + 5; //a = 28

4.

91


Qt , (. . 4.12). (shared data). Qt
.
, 1.
, 1.
0, . ,
.
. 4.12 , . . ,
shared_null ( ). , .
, ,
. , ,
, . . ,
, . ,

0, .

. 4.12.

92

I. Qt

. 4.12 :
QString str1;
QString str2;
str1 = " "
str2 = str1;

//
//
//
//
//
str1 += " "; //

shared_null
shared_null
, = 1
str1 str2
= 2
str1

, ,
.
, . . , , , , .
. Qt
Java STL.
foreach.
,
, .
QString
.
.
QVariant , .

II



.
.

5.

6.

7.

8.

9.

10.

11.

12.

13.



,
.

(GUI, Graphical
User Interface). (widgets) " " . , , ,
, . Qt :
, .
, , .
, . 5.1, . . , , : QMenu (. 32), QGLWidget (. 23), QMainWindow (. 35),
QGraphicsView (. 21).

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

. 5.1.

96
II.

5.

97

setGeometry() "" ,
(layouts) (. 6). show(),
hide().


, , ,
show(), , - .

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

, , . .
. , ,
. Qt::WindowFlags
,
( . .).
, , (. 5.2) ,
"|".
setWindowFlags(). :
wgt.setWindowFlags(Qt::Window | Qt::WindowTitleHint |
Qt::WindowStaysOnTopHint);

. 5.2.

II.

98


Qt::WindowStaysOnTopHint , ,
.

. 5.2 .
- setWindowTitle() .
. :
wgt.setWindowTitle("My Window");

setEnabled() (enabled) (disabled)


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


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

. 5.3. ( )

x(), y() pos() .


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

5.

99

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


(Backing Store) ,

(PaintEvent). , .
,
, , .
.
autoFillBackground, false. , , , . true, , . :
wgt.setAutoFillBackground(true);


,
.

(. 13),
setPalette() . ,
. 5.4,
, .

. 5.4.

5.1. main.cpp

#include <QtGui>
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QWidget
wgt;
QWidget* pwgt1 = new QWidget(&wgt);
QPalette pal1;

II.

100
pal1.setColor(pwgt1->backgroundRole(), Qt::blue);
pwgt1->setPalette(pal1);
pwgt1->resize(100, 100);
pwgt1->move(25, 25);
pwgt1->setAutoFillBackground(true);

QWidget* pwgt2 = new QWidget(&wgt);


QPalette pal2;
pal2.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();
}

5.1 wgt,
( pwgt1 pwgt2) .
setPalette() , (). resize()
- ( move())
setAutioFillBackround() autoFillBackground true,
.
- ( pwgt2) ,
. , stone.jpg pal2.


() QCursor QCursor. ,
. , . , , , , ,
.
setCursor(), . 5.1 .
5.1. CursorShape Qt

ArrowCursor

, . ,

5.

101
5.1 ()

UpArrowCursor

CrossCursor

. ,

WaitCursor

IbeamCursor

I- (I-beam cursor)
.
,

PointingHandCursor

ForbiddenCursor

, , ,

WhatsThisCursor

, -

SizeVerCursor

SizeHorCursor

SizeBDiagCursor

SizeFDiagCursor

SizeAllCursor

SplitVCursor

,
. 6

SplitHCursor

,
. 6

OpenHandCursor

ClosedHandCursor

BlankCursor


QApplication::setOverrideCursor() . , , , ,
. -

II.

102

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

QCursor pos(),
. setPos() .
, QBitmap. ,
. ,
color1, , ,
color0 .
QPixmap.
, . 5.5, .

. 5.5.

5.2.

#include <QtGui>
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.

103

QCursor setCursor() .


QStackedWidget QFrame ,
, , .
addWidget().
. removeWidget(), .
setCurrentWidget()
setCurrentIndex(), .
indexOf().
.

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

Box | Plain

HLine | Plain

Box | Raised

HLine | Raised

Box | Sunken

HLine | Sunken

Panel | Plain

VLine | Plain

Panel | Raised

VLine | Raised

Panel | Sunken

VLine | Sunken

WinPanel | Plain

StyledPanel | Plain

WinPanel | Raised

StyledPanel | Raised

WinPanel | Sunken

StyledPanel | Sunken

II.

104


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

, setFrameStyle() , setLineWidth() .


QAbstractScrollArea QFrame
.
QScrollArea.
,
, /
. C .
, ,
Qt::ScrollBarAlwaysOn. :
QScrollArea sa;
sa.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
sa.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);

. 5.6,
, .
. QAbstractScrollArea::viewport(). verticalScrollBar()
horizontalScrollBar()
( QScrollBar) . cornerWidget()
, .

. 5.6.

5.

105

setWidget(),
.
.
widget(). QScrollArea
removeChild().
,
. 5.7. .

. 5.7.

5.3. main.cpp

#include <QtGui>
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QScrollArea sa;
QWidget*
QPixmap

pwgt = new QWidget;


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,

106

II.

setPalette() . ,
setAutoFillBackground() .
( pwgt)
setFixedSize(). s
setWidget() .

( ). QWidget . , Qt, QWidget


.
- : . , (show) (hide), , .
-
.
, - , .
. Qt , . .
QFrame QWidget ,
.
QStackedWidget , ,
. , ,
.
.
, .

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

(layout managers)
,
. ,
. .

II.

108

QLayout. , : QObject QLayoutItem (. 6.1).


QLayout.

. 6.1.

. 6.2.


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

QLayout QGridLayout QBoxLayout (. 6.1).


QGridLayout , QBoxLayout
QHBoxLayout QVBoxLayout .
. . setSpacing(),
. setMargin()
, 5
10 . 6.2
.
addWidget() , addLayout() .
- , removeWidget(), .

.
, .

-. , , . . .

6.

109



QBoxLayout QHBoxLayout QVBoxLayout.

QBoxLayout
QBoxLayout , . ,
:
LeftToRight , ;
RightToLeft , c ;
TopToBottom , ;
BottomToTop , .

QLayout :
insertWidget(), insertLayout(), insertSpacing() insertStretch().
addSpacing() .
QBoxLayout addWidget() , , ( ). . 6.3.

. 6.3.

6.1. main.cpp

#include <QtGui>
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
QBoxLayout* pbxLayout = new QBoxLayout(QBoxLayout::LeftToRight);

II.

110
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 A, B C, QBoxLayout::addWidget(), .
QBoxLayout::LeftToRight,
. QWidget::setLayout() wgt.
, 6.1 , . .
( pcmdA, pcmdB pcmdC) , ,
, .
- ? ,
(memory leak)?
, . . - .
setLayout()
, wgt.
,
addStretch(). , , . . 6.4 .

. 6.4. A B

, . 6.5, ,
. 6.3,
.

. 6.5. A B

6.

111

6.2. main.cpp

#include <QtGui>
int main(int argc, char** argv)
{
QApplication app(argc, 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 A B.
QLayout::addWidget() ( pcmdA).
QBoxLayout::addStretch() ,
( pcmdB).
QHBoxLayout QVBoxLayout, QBoxLayout, ,
, , . . .
,
.

QHBoxLayout
QHBoxLayout ,
. QBoxLayout, , , . ,
QHBoxLayout, . 6.6.

. 6.6.

II.

112
6.3. main.cpp

#include <QtGui>
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 A, B C ( 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.

113


,
. addLayout(), .
. 6.8 . QVBoxLayout QHBoxLayout.

. 6.8.

6.4. Layout.cpp

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

pcmdA
pcmdB
pcmdC
pcmdD

=
=
=
=

new
new
new
new

QPushButton("A");
QPushButton("B");
QPushButton("C");
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();
}

II.

114

6.4 , . 6.8. , ,
, .
setMargin(), ,
setSpacing() 15 ,
. pcmdC pcmdD.
pcmdA pcmdB QLayout::addWidget()
pvbxLayout, QBoxLayout::
addLayout() phbxLayout.
QWidget::setLayout() pvbxLayout wgt.

QGridLayout
QGridLayout,
. ,
.

, 2 , QformLayout, ,
QGridLayout. , , ,
. addRow(),
: .

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

setRowStretch() setColumnStretch(),
, . setSpacing().
, . 6.9, A, B, C D
2 2 .

. 6.9.

6.5. main.cpp

#include <QtGui>
int main(int argc, char** argv)

6.

115

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

pcmdA
pcmdB
pcmdC
pcmdD

=
=
=
=

new
new
new
new

QPushButton("A");
QPushButton("B");
QPushButton("C");
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.
setMargin() 5 . setSpacing()
15 .
addWidget(),
, .
, . 6.10, .
QValueStack QRegExp, 4.

. 6.10.

II.

116
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.76.11). resize() show() .
6.7. Calculator.h

#ifndef _Calculator_h_
#define _Calculator_h_
#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);
QPushButton* createButton(const QString& str);
void
calculate
(
);
public slots:
void slotButtonClicked();
};
#endif

//_Calculator_h_

6.

117

Calculator, 6.7, :
m_plcd , m_stk m_strDisplay , . createButton()
, calculate() ,
m_stk. slotButtonClicked() .
6.8. Calculator.cpp. Calculator

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


{
m_plcd = new QLCDNumber(12);
m_plcd->setSegmentStyle(QLCDNumber::Flat);
m_plcd->setMinimumSize(150, 50);
QChar aButtons[4][4] = {{'7',
{'4',
{'1',
{'0',
};

'8',
'5',
'2',
'.',

'9',
'6',
'3',
'=',

'/'},
'*'},
'-'},
'+'}

//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);
}

( 6.8) , 12. QLCDNumber::Flat, setSegmentStyle(),


. setMinimumSize()
. aButtons
. addWidget(), , .
CE, createButton(), addWidget() (1,3) (. . ).
createButton() addWidget().

II.

118
6.9. Calculator.cpp. createButton()

QPushButton* Calculator::createButton(const QString& str)


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

createButton(), 6.9,
. setMinimumSize() , clicked()
slotButtonClicked() connect().
6.10. Calculator.cpp. calculate()

void Calculator::calculate()
{
double dOperand2
= m_stk.pop().toDouble();
QString strOperation = m_stk.pop();
double dOperand1
= m_stk.pop().toDouble();
double dResult
= 0;
if (strOperation == "+") {
dResult = dOperand1 + dOperand2;
}
if (strOperation == "-") {
dResult = dOperand1 dOperand2;
}
if (strOperation == "/") {
dResult = dOperand1 / dOperand2;
}
if (strOperation == "*") {
dResult = dOperand1 * dOperand2;
}
m_plcd->display(dResult);
}

calculate() ( 6.10) , m_stk. dOperand2 ,


double. strOperation . dOperand1 , double. if , , , dResult. dislay()
dResult ( m_plcd).

6.

119

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_plcd->display(m_strDisplay);
}
else {
if (m_stk.count() >= 2) {
m_stk.push(QString().setNum(m_plcd->value()));
calculate();
m_stk.clear();
m_stk.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");
}
}
}

slotButtonClicked() ( 6.11) , , QPushButton, str


. "CE",
0. , m_strDisplay, . ,
. ,
.
calculate() .
clear() , , . "=",
.

II.

120


.

<Tab>, , , . ,
. . 6.11 .
C B,
A.

. 6.11.

. 6.12.

QWidget::setTabOrder(), , , .
, . 6.11, , . 6.12:
QWidget::setTabOrder(A, B);
QWidget::setTabOrder(B, C);

QSplitter

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

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

6.

121

QSplitter
spl(Qt::Vertical);
QTextEdit*
ptxt1 = new QTextEdit;
QTextEdit*
ptxt2 = new QTextEdit;
spl.addWidget(ptxt1);
spl.addWidget(ptxt2);
ptxt1->setPlainText("Line1\n"
"Line2\n"
"Line3\n"
"Line4\n"
"Line5\n"
"Line6\n"
"Line7\n"
);
ptxt2->setPlainText(ptxt1->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.
. , .

.
, .


,
.

. , (, ).


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

AlignLeft

0x0001

AlignRight

0x0002

AlignHCenter

0x0004

AlignJustify

0x0008

AlignTop

0x0010

7.

123
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 <QtGui>
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QLabel lbl("<H1><CENTER>QLabel HTML Demo</CENTER></H1>"
"<H2><CENTER>Image</CENTER><H2>"
"<CENTER><IMG BORDER=\"0\" SRC=\"img.jpg\"></CENTER>"
"<H2><CENTER>List</CENTER><H2>"
"<OL><LI>One</LI>"
"
<LI>Two</LI>"
"
<LI>Three</LI>"

II.

124

"</OL>"
"<H2><CENTER>Font Style</CENTER><H2>"
"<CENTER><FONT COLOR=RED>"
"
<B>Bold</B>, <I>Italic</I>, <U>Underline</U>"
"</FONT></CENTER>"
"<H2><CENTER>Table</CENTER></H2>"
"<CENTER> <TABLE>"
"
<TR BGCOLOR=#ff00ff>"
"
<TD>1,1</TD><TD>1,2</TD><TD>1,3</TD><TD>1,4</TD>"
"
</TR>"
"
<TR BGCOLOR=YELLOW>"
"
<TD>2,1</TD><TD>2,2</TD><TD>2,3</TD><TD>2,4</TD>"
"
</TR>"
"
<TR BGCOLOR=#00f000>"
"
<TD>3,1</TD><TD>3,2</TD><TD>3,3</TD><TD>3,4</TD>"
"
</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 <QtGui>
int main(int argc, char** argv)
{
QApplication app(argc, argv);

7.

125

QPixmap pix;
pix.load("mira.jpg");
QLabel lbl;
lbl.resize(pix.size());
lbl.setPixmap(pix);
lbl.show();
return app.exec();
}

7.2, QPixmap. load() mira.jpg.


lbl QLabel.
resize() . , , setPixmap() .
setBuddy()
. &, , ,
. <Alt>
, setBuddy(). . 7.3 ,
7.3 .

. 7.3.
&

7.3. main.cpp

#include <QtGui>
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);

II.

126
//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
. . ,
setBuddy() , .
Age (), ( QSpinBox) .
.
, , , HTML-. III.
. , QLabel
linkActivated(),
, .
, , ,
QLabel , Web- (
QDesktopServices::openUrl()).
setOpenExternalLinks() true. :
QLabel* plbl =
new QLabel("<A HREF=\"www.bhv.ru\">http://www.bhv.ru</A>");
lbl.setOpenExternalLinks(true);


(progress bar) , . . ,
. , , . ,
. QProgessBar
QProgressBar. ,

7.

127

, setOrientation() Qt::Vertical
.
, . 7.4,
. 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.4, ,
. 7.4.
7.5. Progress.h

#ifndef _Progress_h_
#define _Progress_h_
#include <QWidget>
class QProgressBar;
// ======================================================================
class Progress : public QWidget {
Q_OBJECT
private:
QProgressBar* m_pprb;
int
m_nStep;
public:
Progress(QWidget* pobj = 0);

II.

128
public slots:
void slotStep ();
void slotReset();
};
#endif

//_Progress_h_

7.5 Progress.h, Progress,


QWidget. :
, . :
slotStep() slotReset(). , .
7.6. Progress.cpp

#include <QtGui>
#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);
}
// ---------------------------------------------------------------------void Progress::slotStep()
{
m_pprb->setValue(++m_nStep);
}

7.

129

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

( 7.6) m_nStep 0. m_pprb setRange() ,


5, setMinimumWidth() , .
setAlignment() Qt::AlignCenter
(. . 7.1). : Step ()
Reset (), slotStep() slotReset().
slotStep() m_nStep 1
QProgressBat::setValue() . slotReset()
m_nStep 0 , QProgressBat::reset(),
. - ,
, Progress
QVBoxLayout, , , -.


QLCDNumber
QLCDNumber. , , .
. ,
, setSmallDecimalPoint()
true false .
setNumDigits(). ,
, overflow().
Outline,
, setSegmentStyle() :
QLCDNumber::Outline, QLCDNumber::Filled QLCDNumber::Flat. . 7.2
.
7.2.

Outline

Flat

Filled

II.

130

, ,
.
setMode(), :
QLCDNumber::Bin (), QLCDNumber::Oct (), QLCDNumber::Dec () QLCDNumber::Hex ().
setBinMode(), setOctMode(), setDecMode() setHexMode()
. , . 7.5, ,
.

. 7.5.

7.7. main.cpp

#include <QtGui>
int main (int argc, char** argv)
{
QApplication app(argc, argv);
QWidget
wgt;
QLCDNumber* plcd = new QLCDNumber;
QSpinBox*
pspb = new QSpinBox;
plcd->setSegmentStyle(QLCDNumber::Filled);
plcd->setMode(QLCDNumber::Hex);
pspb->setFixedHeight(30);
QObject::connect(pspb, SIGNAL(valueChanged(int)),
plcd, SLOT(display(int))
);
//Layout setup
QVBoxLayout* pvbxLayout = new QVBoxLayout;
pvbxLayout->addWidget(plcd);
pvbxLayout->addWidget(pspb);
wgt.setLayout(pvbxLayout);
wgt.resize(250, 150);
wgt.show();
return app.exec();
}

7.

131

7.7 ( plcd)
( pspb). setSegmentStyle()
. setMode()
QLCDNumber::Hex .
setFixedHeight() , 30.
valueChanged() display() .

. , . ,
HTML. .
.
.

, . , ,
.

,
, ,
.
""

. ,
, .
(on) (off).

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


,
, setText().
QAbstractButton text().
setIcon().
setIconSize()
, ( ). iconSize(). , , icon().


QAbstractButton :
clicked() ;
pressed() ;

8. ,

133

released() ;
toggled() , -


QAbstractButton :
isDown() true, . -

, ,
setDown();
isChecked() true, -

. , , setChecked();
, . . , isEnabled()

true. setEnabled().

, ,
Ok Cancel () .
" ". , ,
. QPushButton QPushButton.
:
QPushButton* pcmd = new QPushButton("My Button");

( ) ; ,
, , . . .
, licked().
, <Enter>,
, ( ). , setDefault().
, . 8.1,
:
Normal Button ( ) ,

. ;
Toggle Button () : -

, "" "". , , ;
Flat Button ( )

. . , , , " " ;

II.

134

, Pixmap Button ( -

) ,
.

. 8.1.

8.1. main.cpp

#include <QtGui>
int main (int argc, char** argv)
{
QApplication app(argc, argv);
QWidget
wgt;
QPushButton* pcmdNormal = new QPushButton("&Normal Button");
QPushButton* pcmdToggle = new QPushButton("&Toggle Button");
pcmdToggle->setCheckable(true);
pcmdToggle->setChecked(true);
QPushButton* pcmdFlat = new QPushButton("&Flat Button");
pcmdFlat->setFlat(true);
QPixmap pix("aloena.jpg");
QPushButton* pcmdPix = new QPushButton("&Pixmap Button");
pcmdPix->setIcon(pix);
pcmdPix->setIconSize(pix.size());
//Layout setup
QVBoxLayout* pvbxLayout = new QVBoxLayout;
pvbxLayout->addWidget(pcmdNormal);
pvbxLayout->addWidget(pcmdToggle);
pvbxLayout->addWidget(pcmdFlat);
pvbxLayout->addWidget(pcmdPix);
wgt.setLayout(pvbxLayout);
wgt.show();
return app.exec();
}

8.1 , . 8.1.
( pcmdNormal). - (

8. ,

135

pcmdToggle) , ,
setCheckable() true .
setChecked() true .

( pcmdFlat) .
setFlat() true .
pix, aloena.jpg, . ( pcmdPix),
setIcon() . setIconSize()
, ,
size() QPixmap.

(. 8.2). , , Microsoft Internet
Explorer. Start () Windows
. , setMenu()
.
(. 11).

. 8.2.

8.2. main.cpp

#include <QtGui>
int main (int argc, char** argv)
{
QApplication app(argc, argv);
QPushButton cmd("Menu");
QMenu*
pmnu = new QMenu(&cmd);
pmnu->addAction("Item1");
pmnu->addAction("Item2");
pmnu->addAction("&Quit", &app, SLOT(quit()));
cmd.setMenu(pmnu);
cmd.show();
return app.exec();
}

8.2 cmd pmnu.


addAction() (. 32). Quit ()

II.

136

quit() ,
, .
setMenu().

, . , . QCheckBox
QCheckBox.

, QListWidget
(. 11 12).


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

. 8.3.

8.3. main.cpp

#include <QtGui>
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QWidget
wgt;
QCheckBox* pchkNormal = new QCheckBox("&Normal Check Box");
pchkNormal->setChecked(true);
QCheckBox* pchkTristate = new QCheckBox("&Tristate Check Box");
pchkTristate->setTristate(true);
pchkTristate->setCheckState(Qt::PartiallyChecked);
//Layout setup
QVBoxLayout* pvbxLayout = new QVBoxLayout;

8. ,

137

pvbxLayout->addWidget(pchkNormal);
pvbxLayout->addWidget(pchkTristate);
wgt.setLayout(pvbxLayout);
wgt.show();
return app.exec();
}

8.3 pchkNormal pchkTristate.


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

radio button ,
. ,
, .
(. 8.4),
: (on) (off).
<>, .
QRadioButton QRadioButton.
, ,
.
. , ,
QGroupBox.
,
. &
.

, ,
. , QComboBox (. 11).

. 8.4.

II.

138
8.4. main.cpp

#include <QtGui>
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QGroupBox gbx("&Colors");
QRadioButton* pradRed
= new QRadioButton("&Red");
QRadioButton* pradGreen = new QRadioButton("&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();
}

8.4 gbx. pradRed, pradGreen pradBlue (pradGreen)


setChecked() true.
gbx, QVBoxLayout (. . 8.4).


, , .
. ,
. , , QRadioButton
.
QGroupBox ,
.
, ,
, ,
(. 8.5). QGroupBox.
, . 8.5, , . , Red () ,

8. ,

139

. Light ()
, Exit () .
main.cpp 8.5.

. 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.h

#ifndef _Buttons_h_
#define _Buttons_h_
#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;

II.

140
public:
Buttons(QWidget* pwgt = 0);
public slots:
void slotButtonClicked();
};
#endif

//_Buttons_h_

8.6, Buttons,
QGroupBox. m_pchk m_pradRed, m_pradGreen,
m_pradBlue . ,
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);
pvbxLayout->addWidget(pcmd);
setLayout(pvbxLayout);
slotButtonClicked();
}

8. ,

141

Buttons ( 8.7) setCheckable()


true , "" setChecked().
( pradRed, pradGreen pradBlue)
setChecked() c true. clicked()
slotButtonClicked().
Light () ( m_pchk)
setChecked().
Exit () ( pcmd). clicked() quit() .
QVBoxLayout.
slotButtonClicked() .
8.8. Buttons.cpp. slotButtonClicked()

void Buttons::slotButtonClicked()
{
QPalette pal
= palette();
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));
}
setPalette(pal);
}

8.8 slotButtonClicked(),
Light () nLight, . if
- isChecked().
, QWidget::backgroundRole() QPalette::setColor()
QWidget::setPalette(). 13.

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

142

II.

clicked(), ,
.
, . . , .
,
. "--".
.
, , .



.
, - IBM

, , , , , , ,
() , .

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


, QAbstractSlider, , .
setOrientation(), Qt::Horizontal, Qt::Vertical.


setRange().
( ),
( ). setMinimum() setMaximum() . ,
1 10, :
psld->setRange(1, 10);

psld->setMinimum(1);
psld->setMaximum(10);

II.

144


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


- ,
setValue(). value().
sliderMoved(int) .
valueChanged() sliderMoved(int)
.
setTracking().
false, , valueChanged() .
,
, sliderPressed()
sliderReleased().

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

NoTicks

TicksAbove

TicksBelow

TicksBothSides

9.

145

setTickInterval() . , . .
.
, . 9.1, , .
. 9.1. ,

9.1. main.cpp

#include <QtGui>
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() , , .

II.

146

, ,
.
, setValue() 3,
, .
,
setTickInterval() 2. setTickmarks()
. connect() valueChanged(int)
setNum(int).
wgt
.


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

. 9.2.

. 9.3. ,

9.

147

9.2. main.cpp

#include <QtGui>
int main (int argc, char** argv)
{
QApplication app(argc, argv);
QWidget
wgt;
QLCDNumber* plcd = new QLCDNumber(4);
QScrollBar* phsb = new QScrollBar(Qt::Horizontal);
QObject::connect(phsb, SIGNAL(valueChanged(int)),
plcd, SLOT(display(int))
);
//Layout setup
QVBoxLayout* pvbxLayout = new QVBoxLayout;
pvbxLayout->addWidget(plcd);
pvbxLayout->addWidget(phsb);
wgt.setLayout(pvbxLayout);
wgt.resize(250, 150);
wgt.show();
return app.exec();
}

9.2 ( plcd)
( phsb). valueChanged() display() ,
, connect(). , wgt, QVBoxLayout.

QDial QDial.
, . . ,
,
. setWrapping().
setNotchTarget(), , setNotchesVisible(), .
, . 9.4, . .

II.

148
9.3. main.cpp

#include <QtGui>
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).
setRange()
0 100. setNotchTarget() 5, setNotchesVisible() , true.

. 9.4. ,

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

QVBoxLayout .

9.

149

, . QAbstractSlider, , .
,
, . . ,
.
, .
.
, ,
.

10


, , , ,
,
.


.
(drag & drop),
. ,
.


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

,
setEchoMode() Password. , *.
, . 10.1, ,
.
.

. 10.1.

10.

151

10.1. main.cpp

#include <QtGui>
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 QString&)),
plblDisplay, SLOT(setText(const QString&))
);
QLabel*
plblPassword = new QLabel("&Password:");
QLineEdit* ptxtPassword = new QLineEdit;
plblPassword->setBuddy(ptxtPassword);
ptxtPassword->setEchoMode(QLineEdit::Password);
QObject::connect(ptxtPassword, SIGNAL(textChanged(const QString&)),
plblDisplay, SLOT(setText(const QString&))
);
//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). setFrame() , setLineWidth() . setFixedHeight(). , plblText plblPassword, setBuddy().


textChanged() setText() plblDisplay .
QVBoxLayout.

II.

152

setMaxLength(),
, .
maxLength().
QLineEdit :
copy() ;
cut() ;
paste() ( ), .

undo() , redo() . , , isUndoAvailable() isRedoAvailable(), .


-
(validator), . " ".


QTextEdit ,
HTML. QAbstractScrollArea,
, .

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

QTextEdit :
setReadOnly() ;
text() .

:
setPlainText() ;
setHtml() HTML;
copy(), cut() paste() (,

);
selectAll() deselect() ;
clear() .

:
textChanged() ;
selectionChanged() .

QTextCursor, QTextEdit. QTextCursor

10.

153

, .
QTextCursor QTextEdit::textCursor().
QTextEdit QTextDocument, 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.


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

QTextEditor QSyntaxHighlighter
.

zoomIn() zoomOut()
, .

HTML, , , QLabel (. 7).

. 10.2 HTML-.
.
10.2. main.cpp

#include <QtGui>
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QTextEdit
txt;
txt.setHtml("<HTML>"
"<BODY BGCOLOR=MAGENTA>"
"<CENTER><IMG SRC=\"agnetha.jpg\"></CENTER>"

II.

154

"<H2><CENTER>THE WINNER TAKES IT ALL</CENTER></H2>"


"<H3><CENTER>(B.Andersson/B.Ulvaeus)</CENTER><H3>"
"<FONT COLOR=BLUE>"
"<P ALIGN=\"center\">"
"<I>"
"I don't wanna talk<BR>"
"About the things we've gone through<BR>"
"Though it's hurting me<BR>"
"Now it's history<BR>"
"I've played all my cards<BR>"
"And that's what you've done too<BR>"
"Nothing more to say<BR>"
"No more ace to play<BR><BR>"
"The winner takes it all<BR>"
"The loser standing small<BR>"
"Beside the victory<BR>"
"That's her destiny<BR>"
"..."
"</I>"
"</P>"
"</FONT>"
"</BODY>"
"</HTML>"
);
txt.resize(320, 250);
txt.show();
return app.exec();
}

10.2 txt. setHtml()


QTextEdit HTML.

. 10.2. , HTML-

10.

155


QTextDocumentWriter
QTextDocument PlainText ( ), HTML ODF (OpenDocument Format,
).
, OpenOffice.org.
, 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(&printer);

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

(syntax highlighting)

. QTextEdit ,
QSyntaxHighlighter
highlightBlock().

II.

156

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

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

,
QTextDocument, ,
QTextEdit, , QTextDocument. , , QTextBrowser,
QTextFrame, QTextTable, QGraphicsTextItem (. 21) .
, QSyntaxHighlighter,
,
C++ Borland (. 10.3).
10.5. main.cpp

#include <QtGui>
#include "SyntaxHighlighter.h"
int main (int argc, char** argv)
{
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);

10.

157

txt.show();
txt.resize(640, 480);
QFile file(":/SyntaxHighlighter.cpp");
file.open(QFile::ReadOnly);
txt.setPlainText(QLatin1String(file.readAll()));
return app.exec();
}

. 10.3.

( 10.5) txt QTextEdit . fnt setDefaultFont() .



SyntaxHighlighter
; .
pal, , () () . show() -

II.

158

resize(). SyntaxHighlighter.cpp , open() . readAll() setPlainText().


10.6. SyntaxHighlighter.h

#ifndef _SyntaxHighlighter_h_
#define _SyntaxHighlighter_h_
#include <QSyntaxHighlighter>
class QTextDocument;
// ======================================================================
class SyntaxHighlighter: public QSyntaxHighlighter {
Q_OBJECT
private:
QStringList m_lstKeywords;
protected:
enum { NormalState = -1, InsideCStyleComment, InsideCString };
virtual void highlightBlock(const QString&);
QString getKeyword(int i, const QString& str) const;
public:
SyntaxHighlighter(QTextDocument* parent = 0);
};
#endif //_SyntaxHighlighter_h_

( 10.6) SyntaxHighlighter
QSyntaxHighlighter. NormalState, InsideCStyleComment
InsideCString, .
highlightBlock(),
. getKeyword() ,
,
C++ Qt.
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"

10.
<<
<<
<<
<<
<<
<<
<<
<<

"namespace"
"protected"
"->"
"("
"]"
"="
":"
"|"

<<
<<
<<
<<
<<
<<
<<
<<

159
"switch"
"new"
">>"
")"
"+"
"!"
"&"
"SLOT"

<<
<<
<<
<<
<<
<<
<<
<<

"case"
"return"
"<<"
"{"
"-"
"."
"emit"
"slots"

<<
<<
<<
<<
<<
<<
<<
<<

"public" <<
"using"
<<
">"
<<
"}"
<<
"*"
<<
","
<<
"connect" <<
"signals";

"private"
"true"
"<"
"["
"/"
";"
"SIGNAL"

m_lstKeywords
( 10.7).
10.8. SyntaxHighlighter.cpp. highlightBlock()

/*virtual*/ void SyntaxHighlighter::highlightBlock(const QString& 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) == "\"" || str.mid(i, 1) == "\'") {
if (str.mid(i 1, 2) != "\\\""
&& str.mid(i 1, 2) != "\\\'"
) {
nState = NormalState;
setFormat(nStart, i nStart + 1, Qt::cyan);
}
}
}
else {
if (str.mid(i, 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);
}

II.

160

else if (str.mid(i, 2) == "/*") {


nStart = i;
nState = InsideCStyleComment;
}
else if (str.mid(i, 1) == "\"" || str.mid(i, 1) == "\'") {
nStart = i;
nState = InsideCString;
}
else {
QString strKeyword = getKeyword(i, str);
if (!strKeyword.isEmpty()) {
setFormat(i, strKeyword.length(), Qt::white);
i += strKeyword.length() 1;
}
}
}
}
if (nState == InsideCStyleComment) {
setFormat(nStart, str.length() nStart, Qt::darkGray);
}
if (nState == InsideCString) {
setFormat(nStart, str.length() nStart, Qt::cyan);
}
setCurrentBlockState(nState);
}

highlightBlock() ,
. highlightBlock()
, . :
NormalState , ,

(. 10.5);
InsideCString , ,

Qt::cyan;
InsideCStyleComment ,

/*...*/, - Qt::darkGray.
nState (. 10.8),
previousBlockState(). InsideCStyleComment InsideCString. "*/" , , nState NormalState - , i , . . .
InsideCString
(" '), , \, . . , \",
,
. , -

10.

161

, .
if , , .
, , , . . . //, , #, (
QString::isNumber()) ++ Qt. ( 10.9) getKeyword().
, .
i , .
InsideCStyleComment InsideCString
/* " .
, InsideCStyleComment
InsideCString,
.
setCurrentState().
10.9. SyntaxHighlighter.cpp. getKeyword()

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


{
QString strTemp = "";
foreach (QString strKeyword, m_lstKeywords) {
if (str.mid(nPos, strKeyword.length()) == strKeyword) {
strTemp = strKeyword;
break;
}
}
return strTemp;
}

getKeyword() C++
Qt. m_lstKeyword
foreach
.
strTemp, (break),
.
, , , .
, , , ,
, ;
QSyntaxHighlighter.

II.

162


QAbstractSpinBox . (. . 5.1):
QSpinBox ;
QDateTimeEdit ;
QDoubleSpinBox , double.

,
, . setWrapping() true.
stepUp() stepDown(),
.
C setSpecialValueText() ,
, :
pspb->setSpecialValueText("default");

QSpinBox .
, , setRange(). setValue(), value(). valueChanged(): int,
const QString&.
setPrefix() setSuffix().
, ,
:
pspb->setPrefix("(");
pspb->setSuffix(")");

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

. 10.4.

10.10. main.cpp

#include <QtGui>
int main (int argc, char** argv)

10.

163

{
QApplication app(argc, argv);
QSpinBox
spb;
spb.setRange(1, 100);
spb.setSuffix(" MB");
spb.setButtonSymbols(QSpinBox::PlusMinus);
spb.setWrapping(true);
spb.show();
spb.resize(50, 30);
QApplication::setStyle(new QWindowsStyle);
return app.exec();
}

10.10 spb.
setRange(). setSuffix() "
" , setButtonSymbols(), PlusMinus, +/. setWrapping() . ,
QWindowStyle.


,
.
dateTimeChanged().
QDateTimeEdit QDateTime.
, . 10.5, , .

. 10.5.

10.11. main.cpp

#include <QtGui>
int main (int argc, char** argv)
{
QApplication app(argc, argv);
QDateTimeEdit dateTimeEdit(QDateTime::currentDateTime());
dateTimeEdit.show();
return app.exec();
}

II.

164

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


QValidator ( ) . QValidator
setValidator(), QComboBox QLineEdit.
QIntValidator QDoubleValidator.
, QValidator
validate(), . :
QValidator::Invalid ;
QValidator::Intermediate -

. , 50 100,
1 ;
QValidator::Acceptable .

, . 10.6, , . , , .

. 10.6. ,
,

10.12. NameValidator. main.cpp

class NameValidator : public QValidator {


public:
NameValidator(QObject* parent) : QValidator(parent)
{
}
virtual State validate(QString& str, int& pos) const
{
QRegExp rxp = QRegExp("[0-9]");
if (str.contains(rxp)) {
return Invalid;
}
return Acceptable;
}
};

10.

165

10.12, NameValidator QValidator.


validate(),
. rxp (. 4),
, 0
9. if QString::contains()
. , , Invalid, , , Acceptable .
10.13. . main.cpp

int main (int argc, char** argv)


{
QApplication app(argc, argv);
QWidget
wgt;
QLabel* plblText =
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(plblText);
pvbxLayout->addWidget(ptxt);
wgt.setLayout(pvbxLayout);
wgt.show();
return app.exec();
}

10.13 ( plblText),
( ptxt) ( pnameValidator).
setValidator() ( ptxt),
setBuddy().

, . , (drag & drop).

166

II.

QLineEdit . QTextEdit.
QAbstractScrollArea, ,
. QTextDocumentWriter ODF, HTML, QPrinter PDF-.
(QSpinBox) .
, .
QComboBox (. 11)
QLineEdit setValidator().

11


,
.
.


, . ,
, .
QListWidget, QTreeWidget QTableWidget "", 12.
, , , .
"-", ,
, , . ...


QListWidget , . . , addItem().
:
QListWidgetItem. , clear().
QListWidgetItem . , , QListWidget::addItem().
, QListWidgetItem , .
clone().


,
QStringList, (. 4), insertItems().
insertItem(), -

II.

168

. QListWidgetItem insertItem(). addItem() ,


. , QListWidgetItem::setIcon() .
, , . QListWidget
setItemWidget() itemWidget(). setItemWidget() , .
, ,
itemWidget() .
!
.

. 11.1 ,
.

. 11.1.

11.1. main.cpp

#include <QtGui>
int main(int argc, char** argv)
{
QApplication
app(argc, argv);
QStringList
lst;
QListWidget
lwg;
QListWidgetItem* pitem = 0;
lwg.setIconSize(QSize(48, 48));
lst << "Linux" << "Windows" << "MacOS" << "OS2";
foreach(QString str, lst) {
pitem = new QListWidgetItem(str, &lwg);
pitem->setIcon(QPixmap(str + ".jpg"));
}
lwg.resize(125, 175);
lwg.show();
return app.exec();
}

11.1 lwg.
setIconSize() .

11.

169

lst . foreach,
. setIcon() -

QListWidget::currentItem(), .
, selectedItems(),

. ,
setSelectionMode(),
QAbstractItemView, QAbstractItemView::MultiSelection.
, , ,
QAbstractItemView::NoSelection,
QAbstractItem::SingleSelection.
itemClicked().
itemDoubleClicked()
QListWidgetItem*.
itemSelectionChanged().


,
QListWidgetItem::setFlags()
Qt::ItemIsEditable . :
pitem->setFlags(Qt::ItemIsEditable | Qt::ItemIsEnabled);

<F2>. QListWidget itemChanged(QListWidgetItem*) itemRenamed(QListWidgetItem*).


(
), ,
(drag & drop).
, . 11.2, .

. 11.2.

II.

170
11.2. main.cpp

#include <QtGui>
int main(int argc, char** argv)
{
QApplication
app(argc, argv);
QListWidget
lwg;
QListWidgetItem* pitem = 0;
QStringList
lst;
lwg.setIconSize(QSize(48, 48));
lwg.setSelectionMode(QAbstractItemView::MultiSelection);
lwg.setViewMode(QListView::IconMode);
lst << "Linux" << "Windows" << "MacOS" << "OS2";
foreach(QString str, lst) {
pitem = new QListWidgetItem(str, &lwg);
pitem->setIcon(QPixmap(str + ".jpg"));
pitem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable |
Qt::ItemIsEditable | Qt::ItemIsDragEnabled);
}
lwg.resize(135, 135);
lwg.show();
return app.exec();
}

11.2 lwg. setSelectionMode() . setViewMode()


QListView::IconMode .
lst, . lwg
foreach. setFlags()
, (Qt::ItemIsEnabled),
(Qt::ItemIsSelectable), (Qt::ItemIsEditable) (Qt::ItemIsDragEnabled).
QListWidget . setFlow(),
QListView. QListView::
TopToBottom, .


sortItems().
Qt::AscendingOrder , Qt::DescendingOrder . , , . , -

11.

171

, QListWidgetItem
operator<().


QTreeWidget
.
. , , .
setItemWidget() . ,
. ,
.
, ,
. , .
11.3.

QTreeWidgetItem* ptwi = new QTreeWidgetItem(pTreeView);


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

(. 11.3) ( pwti)
Qt::ItemIsUserCheckable, .
, , . . 11.3
.

. 11.3.

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

QTreeWidgetItem . QTreeWidgetItem clone() .


addChildren() insertChildren() .
,
QTreeWidgetItem::setIcon(), -

II.

172

QTreeWidgetItem::setText(). .
. 11.4 . Local
Disk(C) ().

. 11.4.

11.4. main.cpp

#include <QtGui>
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QTreeWidget twg;
QStringList lst;
lst << "Folders" << "Used Space";
twg.setHeaderLabels(lst);
twg.setSortingEnabled(true);
QTreeWidgetItem* ptwgItem = new QTreeWidgetItem(&twg);
ptwgItem->setText(0, "Local Disk(C)");
ptwgItem->setIcon(0, QPixmap("drive.bmp"));
QTreeWidgetItem* ptwgItemDir = 0;
for (int i = 1; i < 20; ++i) {
ptwgItemDir = new QTreeWidgetItem(ptwgItem);
ptwgItemDir->setText(0, "Directory" + QString::number(i));
ptwgItemDir->setText(1, QString::number(i) + "MB");
ptwgItemDir->setIcon(0, QPixmap("folder.bmp"));
}
twg.setItemExpanded(ptwgItem, true);
twg.resize(250, 110);
twg.show();
return app.exec();
}

(, Windows)
QTreeWidgetItem . -

11.

173

11.4 twg. lst


<<. setHeaderLabels() Folders ()
Used Space ( ). (
ptwgItem) twg. .
20 . setText()
, setIcon() .
setItemExpanded() ptwgItem .
, ,
. .
, setSortingEnabled().
true, false.
. , setSelectionMode()
QAbstractItemView QAbstractItemView::MultiSelection, . ""
QtreeWidget, , :
QTreeWidgetItemIterator it(&twg, QTreeWidgetItemIterator::All);
while (*(++it)) {
qDebug() << (*it)->text(0);
}

,
. , , .
QTreeWidgetItemIterator::All,
. , ,
QTreeWidgetItemIterator::Selected.
, .
QTreeWidget :
itemSelectionChanged() ;
itemClicked(QTreeWidgetItem*, int) ;
itemDoubleClicked(QTreeWidgetItem*, int) ;
itemActivated(QTreeWidgetItem*, int) , -

<Enter> . ,
<Enter> , .
,
.
QTreeWidget (drag & drop). setFlags() ,
Qt::ItemIsDragEnabled, , . :
pitem->setFlags(Qt::ItemIsDragEnabled | Qt::ItemIsEnabled);

174

II.

. ,
setFlags() Qt::ItemIsEditable ( !).


QlistWidget,
sortItems(),
.
QTreeWidgetItem operator<(). , 11.5.
11.5. QTreeWidgetItem::operator<()

bool MyTreeWidgetItem::operator(const QTreeWidgetItem& 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)
. sortColumn() ,
,
QTreeWidget. 0, QDate
.
( bRet).

QTableWidget .
QTableWidgetItem.
QTableWidget::setItem(). setItem() ,
. ,
.
QTableWidgetItem::setText(), QTableWidgetItem::setIcon(). ,
, .
QTableWidgetItem ,
. clone().
, , . setCellWidget().

11.

175

, QLineEdit.
, . 11.5, ,
. .

. 11.5.

11.6. main.cpp

#include <QtGui>
int main(int argc, char** argv)
{
const int n = 3;
QApplication
QTableWidget
QTableWidgetItem*
QStringList

app(argc, argv);
tbl(n, n);
ptwi = 0;
lst;

lst << "First" << "Second" << "Third";


tbl.setHorizontalHeaderLabels(lst);
tbl.setVerticalHeaderLabels(lst);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
ptwi = new QTableWidgetItem(QString("%1,%2").arg(i).arg(j));
tbl.setItem(i, j, ptwi);
}
}
tbl.resize(350, 125);
tbl.show();
return app.exec();
}

11.6 tbl. ,
, .
3 3. ( ),

II.

176

, setHorizontalHeaderLabel()
setVerticalHeaderLabel() .
( ptwi). . setItem()
, .

, , QListWidget
QTreeWidget.


QComboBox .
QListWidget.
() , . ()
, , ().
/ .
addItem(). ,
QStringList addItems(). setDuplicatesEnabled(false),
, . , clear().

currentIndex(), . , -

. Windows,
(). setEditable() true. ,
editTextChanged(const QString&), .
activated()
int ( ), const QString& (
). ,
;
currentIndexChanged(), int const QString& .
, . 11.6, . .

. 11.6.

11.

177

11.7. main.cpp

#include <QtGui>
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QComboBox
cbo;
QStringList lst;
lst << "John" << "Paul" << "George" << "Ringo";
cbo.addItems(lst);
cbo.setEditable(true);
cbo.show();
return app.exec();
}

, 11.7, cbo. lst .


addItems() . setEditable() true .

,
QComboBox QValidator (. 10).

, , , . ,
, . . , .
,
, .
. , setTabEnabled() false.
setCurrentIndex() .
, . 11.7, Linux, Windows, MacOS
OS2. ,
.
11.8. main.cpp

#include <QtGui>
int main(int argc, char** argv)

II.

178
{
QApplication app(argc, argv);
QTabWidget
tab;
QStringList lst;

lst << "Linux" << "Windows" << "MacOS" << "OS2";


foreach(QString str, lst) {
tab.addTab(new QLabel(str, &tab), QPixmap(str + ".jpg"), str);
}
tab.resize(300, 100);
tab.show();
return app.exec();
}

. 11.7.

11.8 tab. addTab() . , , ,


.


QToolBox , .
( ) . addItem().
, insertItem().
, count(). removeItem().
currentWidget(),
.
currentChanged(int),
.
, . 11.8, , .
11.9. main.cpp

#include <QtGui>
int main(int argc, char** argv)

11.

179

{
QApplication app(argc, argv);
QToolBox
tbx;
QStringList lst;
lst << "Linux" << "Windows" << "MacOS" << "OS2";
foreach(QString str, lst) {
tbx.addItem(new QLabel(str, &tbx), QPixmap(str + ".jpg"), str);
}
tbx.resize(100, 80);
tbx.show();
return app.exec();
}

11.9 .
addItem().
,
. . .

. 11.8.

, .
.
QListWidget, QTreeWidget QTableWidget
"-", .
, , :
QListWidget .

( );
QTreeWidget ;
QTableWidget ,

;
QComboBox .

, ;
QTabWidget -

, ;
QToolBox QTabWidget. -

12

-
,
, .

- , 11, . ,
. ,
, , , . ., , , . ,
SQL-
. , , , , , .
Qt , "", , , "-". , "". , "-", Qt, , , , , .
"" :
.

- , , ,
. "-" ,
;
. , -

, .
, . . , ,
,
;
. -

, , - , .
;
. , , -

, . Qt (. 46);

12. -

181

. Qt SQL, -

,
(. 42).

""
, . 12.1.

. 12.1. ""

,
. :

;
-

;
, -

;
, -

, . ,

182

II.

, , . Qt-
QAbstractItemModel (. 12.2). , , .
QAbstractItemModel ,
.
. , , , , ,
, .
, , ,
. .

. 12.2.

QAbstractItemModel ,
. 12.2. QAbstractListModel ,
QAbstractTableModel .
QStandardItemModel . "-", ,
,
.
QStringListModel QAbstractListModel, , .
(QStringList). , . .
,
. .

12. -

183

:
QStringListModel model;
model.setStringList(QStringList() << " "
<< " "
<< " "
);

QAbstractProxyModel , .
. QSortFilterProxyModel. .
QDirModel .
, , , , (, QAbstarctItemView)
(. 12.3). , :
, ,
.

. 12.3.

. 12.4, QAbstactScrollArea, , ,
, , .

QComboBox,
QWidget. QComboBox
setModel(), .

QAbstractItemView,
, , , , . setEditTriggers(), .

II.

184

:
NoEditTriggers ;
DoubleClicked , -

SelectedClicked , -

.
Qt ,
, :
QListView -

.
( );
QTreeView .

;
QTableView .

, QHeaderView QAbstractItemView. ,
QTableView QTreeView .

. 12.4.
( )


, , . .

. , . . .
, . , ,
, , .
,
QItemSelectionModel (. 12.5). ,
, QAbstractItemView::
selectionModel(),

QAbstractItemView::setSelectionModel().
, . 12.6, . .

. 12.5. QItemSelectionModel

12. -

. 12.6.

12.1. main.cpp.

#include <QtGui>
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QWidget
wgt;
QStringListModel model;
model.setStringList(QStringList() << "Item1" << "Item2" << "Item3");
QTreeView* pTreeView = new QTreeView;
pTreeView->setModel(&model);
QListView* pListView = new QListView;
pListView->setModel(&model);
QTableView* pTableView = new QTableView;
pTableView->setModel(&model);
QItemSelectionModel selection(&model);
pTreeView->setSelectionModel(&selection);
pListView->setSelectionModel(&selection);
pTableView->setSelectionModel(&selection);
//Layout setup
QHBoxLayout* phbxLayout = new QHBoxLayout;
phbxLayout->addWidget(pTreeView);
phbxLayout->addWidget(pListView);
phbxLayout->addWidget(pTableView);
wgt.setLayout(phbxLayout);
wgt.show();
return app.exec();
}

185

II.

186

12.1 ( model),
. . ( pTreeView, pListView pTableView) ,
setModel(). (
QItemSelectionModel).
( model).
setSelectionModel() .

QItemSelectionModel::selectedIndexes(). QItemSelectionModel::select(). currentChanged(), selectionChanged(), currentColumnChanged()


currentRowChanged().


. .
( ). Qt
QItemDelegate (. 12.7),
,
.
,
.
QAbstractItemDelegate, QItemDelegate.

. 12.7.

. 12.8.

, , () (. 12.8).
12.2. main.cpp.

#include <QtGui>
// ======================================================================
class SimpleDelegate : public QItemDelegate {
public:
SimpleDelegate(QObject* pobj = 0) : QItemDelegate(pobj)
{
}

12. -

187

void paint(QPainter*
pPainter,
const QStyleOptionViewItem& option,
const QModelIndex&
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);
}
QItemDelegate::paint(pPainter, option, index);
}
};
// ---------------------------------------------------------------------int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QStringListModel model;
model.setStringList(QStringList() << "Item1" << "Item2" << "Item3");
QListView listView;
listView.setModel(&model);
listView.setItemDelegate(new SimpleDelegate(&listView));
listView.viewport()->setAttribute(Qt::WA_Hover);
listView.show();
app.exec();
}

main(), 12.2, setItemDelegate() ( SimpleDelegate).


, Qt::WA_Hover
setAttribute().
SimpleDelegate ( 12.2) paint()
. QPainter.
QStyleOptionViewItem, QStyle. , . , ,
option, ,
. QStyle::State_MouseOver ,
, , ,
. 18.

II.

188

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


, , . . , , ,
. .
. .
,
, . ,
: , .
; , , .
,
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).
QStandardItemModel .
, setData() . data().

12. -

189

. 12.9.

12.3. main.cpp.

#include <QtGui>
int main(int argc, char** argv)
{
QApplication
app(argc, argv);
QStandardItemModel model(5, 3);
for (int nTopRow = 0; nTopRow < 5; ++nTopRow) {
QModelIndex 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(&model);
treeView.show();
return app.exec();
}

, 12.3, , .
index() . , ,
insertRows()
insertColumns(). setData()
.

II.

190

, , QStandardItemModel.
, Qt4 .
, . , . 12.10,
QDirModel
.

. 12.10.

12.4. main.cpp.

#include <QtGui>
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QDirModel
model;
QTreeView
treeView;
treeView.setModel(&model);
treeView.show();
return app.exec();
}

12.4 QDirModel . ! , ,
QTreeView.
index(). : , , ,
. , -

12. -

191

, ( 12.4),
:
QModelIndex index = model.index(QDir::currentPath());
treeView.setRootIndex(index);

setRootIndex() ,
( 12.5), . 12.11.

. 12.11.

12.5. main.cpp. -

#include <QtGui>
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QSplitter
spl(Qt::Horizontal);
QDirModel
model;
QTreeView* pTreeView = new QTreeView;
pTreeView->setModel(&model);
QTableView* pTableView = new QTableView;
pTableView->setModel(&model);
QObject::connect(pTreeView, SIGNAL(clicked(const QModelIndex&)),
pTableView, SLOT(setRootIndex(const QModelIndex&))
);
QObject::connect(pTableView, SIGNAL(activated(const QModelIndex&)),
pTreeView, SLOT(setCurrentIndex(const QModelIndex&))
);

II.

192

QObject::connect(pTableView, SIGNAL(activated(const QModelIndex&)),


pTableView, SLOT(setRootIndex(const QModelIndex&))
);
spl.addWidget(pTreeView);
spl.addWidget(pTableView);
spl.show();
return app.exec();
}

12.5 12.4, , (spl) (


pTableView). (model).
- .
,
, . ,
.
. ,
<Enter>
activated(), ,
setRootIndex() . ,
, .
, , Windows
. , .


(QModelIndex) , ,
.
, ( QModelIndex) .
, .
QAbstractItemModel::data(), ,
DisplayRole. , data() QVariant, .
, , , . - . ,
, , .
. :
DisplayRole :
DecorationRole ;

12. -

193

FontRole ;
ToolTipRole (ToolTip);
WhatThisRole " ?";
TextColorRole ;
BackgroundColorRole .

, . 12.12, Qt::DisplayRole,
Qt::ToolTipRole Qt::DecorationRole.

. 12.12.

12.6. main.cpp.

#include <QtGui>
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QStringList lst;
lst << "Linux" << "Windows" << "MacOS" << "OS2";
QStandardItemModel model(lst.size(), 1);
for (int i = 0; i < model.rowCount(); ++i) {
QModelIndex index = model.index(i, 0);
QString
str
= lst.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(&model);
listView.show();
return app.exec();
}

, 12.6, , . Qt::DisplayRole, Qt::ToolTipRole.


Qt::DecorationRole , ".jpg. ,
.

II.

194


,
QAbstractItemModel, .
(. . 12.2) ,
.
. , . 12.13
, .

. 12.13.

12.7. main.cpp

#include <QtGui>
#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(&model);
list.show();
QTableView table;
table.setModel(&model);
table.show();
return app.exec();
}

12.7
. , setModel(),
. 12.8.
12.8. IntListModel.h

#ifndef _IntListModel_h_
#define _IntListModel_h_

12. -

195

#include <QAbstractListModel>
// ======================================================================
class IntListModel : public QAbstractListModel {
Q_OBJECT
private:
QList<int> m_list;
public:
IntListModel(const QList<int>& list, QObject* pobj = 0);
QVariant data(const QModelIndex& index, int nRole) const;
bool setData(const QModelIndex& index,
const QVariant&
value,
int
nRole
);
int rowCount(const QModelIndex& parent = QModelIndex()) const;
QVariant headerData(int
nSection,
Qt::Orientation orientation,
int
nRole = Qt::DisplayRole
) const;
Qt::ItemFlags flags(const QModelIndex &index) const;
};
#endif //_IntListModel_h_

QAbstractListModel
rowCount() data(). rowCount() ,
data() , QVariant.
headerData(). , QTableView QTreeView. ,
flags() setData().
12.9. IntListModel.cpp.

IntListModel::IntListModel(const QList<int>& list, QObject* pobj/*=0*/)


: QAbstractListModel(pobj)
, m_list(list)
{
}

( 12.9) m_list .

196

II.

12.10. IntListModel.cpp. data()

QVariant IntListModel::data(const QModelIndex& index, int nRole) const


{
if (!index.isValid()) {
return QVariant();
}
return (nRole == Qt::DisplayRole || nRole == Qt::EditRole)
? m_list.at(index.row())
: QVariant();
}

, , , . data() ( 12.10)
QVariant. . ,
(Qt::DisplayRole)
(Qt::EditRole), , ,
, .
, , , QVariant , .
12.11. IntListModel.cpp. setData()

bool IntListModel::setData(const QModelIndex& 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;
}

setData() : ,
( 12.11). isValid().
, ,
(m_list) , replace(). ,
, .
value QVariant QVariant::value<T>(), int (. 4). QVariant::toInt().
dataChanged(), , . ( )
true , false .

12. -

197

12.12. IntListModel. rowCount()

int IntListModel::rowCount(const QModelIndex& parent/*=QModelIndex()*/


) const
{
return m_list.size();
}

rowCount(), 12.12, .
,
(m_list).
12.13. IntListModel. headerData()

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);
}

headerData() 12.13 ,
,
. ,
( ). , "Number",
.
12.14. IntListModel. flags()

Qt::ItemFlags IntListModel::flags(const QModelIndex& index) const


{
Qt::ItemFlags flags = QAbstractListModel::flags(index);
return index.isValid() ? (flags | Qt::ItemIsEditable)
: flags;
}

, flags()
Qt::ItemIsEditable. , ( 12.14).
QAbstractTableModel
, QAbstractListModel. , -

198

II.

QAbstractTableModel columnCount(),
.
, (. 12.14).

. 12.14.

12.15. main.cpp.

#include <QtGui>
// ======================================================================
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 QModelIndex& index, int nRole) const
{
if (!index.isValid()) {
return QVariant();
}
QString str =
QString("%1,%2").arg(index.row() + 1).arg(index.column() + 1);

12. -
return (nRole == Qt::DisplayRole || nRole == Qt::EditRole)
? m_hash.value(index, QVariant(str))
: QVariant();
}
// ----------------------------------------------------------------bool setData(const QModelIndex& index,
const QVariant&
value,
int
nRole
)
{
if (index.isValid() && nRole == Qt::EditRole) {
m_hash[index] = value;
emit dataChanged(index, index);
return true;
}
return false;
}
// ----------------------------------------------------------------int rowCount(const QModelIndex&) const
{
return m_nRows;
}
// ----------------------------------------------------------------int columnCount(const QModelIndex&) const
{
return m_nColumns;
}
// ----------------------------------------------------------------Qt::ItemFlags flags(const QModelIndex& index) const
{
Qt::ItemFlags flags = QAbstractTableModel::flags(index);
return index.isValid() ? (flags | Qt::ItemIsEditable)
: flags;
}
};
// ---------------------------------------------------------------------int main(int argc, char *argv[])
{
QApplication app(argc, argv);
TableModel model(200, 200);
QTableView tableView;
tableView.setModel(&model);
tableView.show();
return app.exec();
}

199

200

II.

, 12.15, ,
12.712.14. ,
columnCount(). .
, . .
Qt::EditRole setData(), flags() Qt::ItemIsEditable. main()
200 200 .
QAbstractItemModel,
QAbstractTableModel.
QAbstractItemModel::index() QAbstractItemModel::parent().
QAbstractItemModel::createIndex(),
.

(Proxy model)
, - , .
, .
. ,
(. 12.15). , .

. 12.15.

.
: , .
, , .
, .
QSortFilterProxyModel , . QSortFilterProxyModel::setFilterRegExp(), QRegExp (. 4).
, .
, .
.

12. -

201

, . 12.16, ,
"E". , .

. 12.16.

12.16. main.cpp.

#include <QtGui>
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(&model);
proxyModel.setFilterWildcard("E*");
QListView* pListView1 = new QListView;
pListView1->setModel(&model);
QListView* pListView2 = new QListView;
pListView2->setModel(&proxyModel);
//Layout setup
QHBoxLayout* phbxLayout = new QHBoxLayout;
phbxLayout->addWidget(pListView1);
phbxLayout->addWidget(pListView2);
wgt.setLayout(phbxLayout);
wgt.show();
return app.exec();
}

II.

202

main(), 12.16, QStringListModel,


.
QSortFilterProxyModel, setSourceMode()
. , "E", setFilterWildcard() "E*".

: ,
.
textChanged() setFilterWildcard()
SortFilterProxyModel, ,
, .

QListView, , .

-
- , : . , . ( Widget):
QListWidget, QTreeWidget QTableWidget.
, "-"
QListView, QTreeView QTableView (. . 12.4).
, , , . , -
(. 12.17),
, QAbstractItemView::model().
- "-", ,
- .
. 12.18 QListWidget ()
QListView (), ,
.
12.17. main.cpp.

#include <QtGui>
int main(int argc, char** argv)
{
QApplication
app(argc, argv);
QStringList
lst;
QListWidget
lwg;
QListWidgetItem* pitem = 0;
lwg.setIconSize(QSize(48, 48));
lst << "Linux" << "Windows" << "MacOS" << "OS2";

12. -

203

foreach(QString str, lst) {


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();
}

12.18 11.1,
- QListWidget .
QListView.
( QListWidget), model() setModel()
listView. ,
selectionModel() setSelectionModel().

. 12.17. -

204

II.

. 12.18.

"" "", .
. -, -
. .
, .
, . .
.
,
.
- "-" , .

13



, , . " ",
.

, , . ,
, . .

. 13.1.

,
palette() QWidget. QPalette,
, . 13.1.
: (Active), (Inactive)
(Disabled). (color roles), . 13.1. (QBrush) (QColor).

II.

206


QPalette , , . , .
13.1. ColorRole QPalette

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.

207

. 13.3. ,

13.1. . 13.3
.
13.1. main.cpp

#include <QtGui>
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().

208

II.

13.1 .
: , !
,
, . 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::setPalette(pal);
...
}

, . ,
. 3- , ,
. ,
. , ,
QApplication::setPalette().

III


... .

14.

15.

16.

14

- ,
.
, ?
" "

, .
- . ,
, . . , , . , , . .
"- ", . ?
, ,
, .
. , . (,
- ). , , , , .
,
, , . , QMouseEvent .
, . ,
mousePressEvent()
clicked().

, Qt virtual
protected. protected.

212

III.


,
. , , . .
, .
Qt : , , . . 14.1 Qt.
. 14.1, QEvent .
. -

. 14.1.

14.

213

,
QEvent QEvent::type().
QEvent accept() ignore(), , . ignore(),
-.
QInputEvent ,
(. 14.1). modifiers().
- <Ctrl>,
<Shift> <Alt>, .
. 14.1.
14.1. Qt

NoModifier

(HEX)
0

ShiftModifier

2000000

<Shift>

ControlModifier

4000000

<Ctrl>

AltModifier

8000000

<Alt>


QCoreApplication::exec(). , ,
QObject. ,
QCoreApplication::exec(). Qt . , , QPaintEvent ""
() , , .
(paintEvent()) .



. ,
.
, .
, , keyPressEvent()
keyReleaseEvent() QKeyEvent.


QKeyEvent
QKeyEvent .
, , ASCII-

214

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- (. 1);
30 39 ,

;
41 5A . , -

ASCII- (. 1);
1000030 1000052 . 35,

. 14.2 12, ;
1000006 100009, 1000025 1000026 -

;
1000010 1000017 ;
1000020 1000023 ;
1000000, 1000001, 1000004 1000005 , . .

.
,
, <Shift>, <Ctrl> <Alt>, modifiers().
text() Unicode-,
. ,
. . key(), (. . 14.1).
, QWidget, .
void MyWidget::keyPressEvent(QKeyEvent* pe)
{
switch (pe->key()) {
case Qt::Key_Z:
if (pe->modifiers() & Qt::ShiftModifier) {
// -
}

14.

215

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_O

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_F1

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

3A

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_F11

100003A

Key_A

41

Key_Enter

1000005

Key_F12

100003B

III.

216

else {
// -
}
break;
default:
QWidget::keyPressEvent(pe); //
}
}

, <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* pe)
{
QPainter painter(this);
QRect
r(40, 40, 100, 100);
if (pe->region().contains(r)) {
painter.drawRect(r);
}
}

IV .

14.

217


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

QMouseEvent
, , ,
.
mousePressEvent(), mouseMoveEvent(), mouseReleaseEvent() mouseDoubleClickEvent().
mousePressEvent() ,
. , , , , ,
. mouseMoveEvent(), mouseReleaseEvent().
mouseMoveEvent() ,
. .
, setMouseTracking() QWidget,
true.
mouseDoubleClickEvent()
.

globalX(), globalY(), x() y(), . pos() globalPos(). pos()
QMouseEvent . ( ), globalPos().
button(), , (. 14.3). buttons() . 14.3 . , , | () .
, - <Ctrl>, <Shift> / <Alt>,
modifiers(), QInputEvent (. . 14.1, . 14.1).

III.

218

14.3. MouseButton
Qt

NoButton

LeftButton

RightButton

MidButton

mouseDoubleClickEvent() mousePressEvent() , . .
. 400 ,
setDoubleClickInterval() QApplication.
. 14.2 , . 14.114.3.
<Ctrl>.

. 14.2. ,

14.1. main.cpp

#include <QtGui>
#include "MouseObserver.h"
int main(int argc, char** argv)
{
QApplication app(argc, argv);
MouseObserver wgt;
wgt.resize(250, 130);
wgt.show();
return app.exec();
}

main()
MouseObserver resize() . show() .

14.

219

14.2. MouseObserver.h

#ifndef _MouseObserver_h_
#define _MouseObserver_h_
#include <QtGui>
// ======================================================================
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 buttonsInfo
(QMouseEvent* pe
);
};
#endif //_MouseObserver_h_

MouseObserver :
mousePressEvent() ;
mouseReleaseEvent() ;
mouseMoveEvent() .

dumpEvent() .
( ) - modifiersInfo() buttonsInfo().
14.3. MouseObserver.cpp

#include "MouseObserver.h"
// ---------------------------------------------------------------------MouseObserver::MouseObserver(QWidget* pwgt /*= 0*/) : QLabel(pwgt)
{
setAlignment(Qt::AlignCenter);
setText("Mouse interactions\n(Press a mouse button)");
}
// ---------------------------------------------------------------------/*virtual*/void MouseObserver::mousePressEvent(QMouseEvent* pe)
{
dumpEvent(pe, "Mouse Pressed");
}

220

III.

// ---------------------------------------------------------------------/*virtual*/void MouseObserver::mouseReleaseEvent(QMouseEvent* pe)


{
dumpEvent(pe, "Mouse Released");
}
// ---------------------------------------------------------------------/*virtual*/ void MouseObserver::mouseMoveEvent(QMouseEvent* pe)
{
dumpEvent(pe, "Mouse Is Moving");
}
// ---------------------------------------------------------------------void MouseObserver::dumpEvent(QMouseEvent* pe, const QString& strMsg)
{
setText(strMsg
+ "\n buttons()=" + buttonsInfo(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()=" + modifiersInfo(pe)
);
}
// ---------------------------------------------------------------------QString MouseObserver::modifiersInfo(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;
}
// ---------------------------------------------------------------------QString MouseObserver::buttonsInfo(QMouseEvent* pe)
{
QString strButtons;
if(pe->buttons() & Qt::LeftButton) {
strButtons += "Left ";
}

14.

221

if(pe->buttons() & Qt::RightButton) {


strButtons += "Right ";
}
if(pe->buttons() & Qt::MidButton) {
strButtons += "Middle";
}
return strButtons;
}

setAlignment() AlignCenter
. mousePressEvent(),
mouseReleaseEvent() mouseMoveEvent(), ,
dumpEvent(), ,
. modifiersInfo()
- , modifiers().
buttonsInfo(). dumpEvent() setText().

QWheelEvent
, , ,

QWheelEvent, QInputEvent (. . 14.1).
QWheelEvent , .
wheelEvent() , , ,
. buttons(), pos()
globalPos(), QMouseEvent,
QWheelEvent delta(), . , ,
.

enterEvent() leaveEvent()
, . , , ,
. enterEvent() QEvent , . leaveEvent() QEvent , .

. QTimerEvent
QTimerEvent , .
timerEvent().
. , ,
QWidget, :

222

III.

void MyClass::timerEvent(QTimerEvent* e)
{
if (event->timerId() == myTimerId) {
// -
}
else {
QWidget::timerEvent(e); //
}
}

38.

(drag & drop)


30.
.

QDragEnterEvent
QDragEnterEvent QDragMoveEvent (. . 14.1). . ,
, , dragEnterEvent().

QDragLeaveEvent
QDragLeaveEvent ,
, , .
dragLeaveEvent().

QDragMoveEvent
,
. dragMoveEvent().

QDropEvent
QDropEvent dropEvent() .


QChildEvent
-. childEvent(), QObject.
QChildEvent::child() .
QChildEvent::added() QChildEvent::removed() -.

QCloseEvent
QCloseEvent . QWidget::close(). QCloseEvent

14.

223

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.3 14.4,
resizeEvent(). ,
.

. 14.3. resizeEvent()

III.

224
14.4. main.cpp

#include <QtGui>
// ======================================================================
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();
}

14.4 main() (
ResizeObserver), resize().
resizeEvent() , . size() QSize, ( width() height()). QString::number().
, QLabel::setText().


, Qt,
, , Qt,
QEvent. QEvent
,

14.

225

QEvent::User, .
QEvent::User 1000 (. . 14.4). -

. :
class MyEvent : public QEvent {
public:
MyEvent() : QEvent((Type)1200)
{
}
QString info()
{
return "CustomEvent";
}
};

QCoreApplication::
sendEvent() QCoreApplication::postEvent(), QObject::event()
QObject::customEvent().

event()
,
, exec() QCoreApplication
QApplication. QApplication ,
. event(),
,
, mousePressEvent() .
. 14.4.

. 14.4.

226

III.

event(), ,
. , ,
, . . .
event(), ,
. , ,
. event() ,
.
event() QEvent.
QEvent, , ,
QEvent . event() ,
. type(). (. 14.4),
.
14.4.

None

ThreadChange

22

Timer

WindowActivate

24

MouseButtonPress

WindowDeactivate

25

MouseButtonRelease

ShowToParent

26

MouseButtonDblClick

HideToParent

27

MouseMove

Wheel

31

KeyPress

WindowTitleChange

33

KeyRelease

WindowIconChange

34

FocusIn

ApplicationWindowIconChange

35

FocusOut

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.

227
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* pe)
{
if (pe->type() == QEvent::KeyPress) {
QKeyEvent* pKeyEvent = static_cast<QKeyEvent*>(pe);

228

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) {
//
}

, ,
, , , , , ,
.

(. 39). QCoreApplication::
processEvents(), ,
. :
for (int i = 0; i < 1000; ++i) {
//
qApp->processEvents(); //
}


, " " .

14.

229

- , , . . . , . ,
. , event(),
. event() . ,
, ,
keyPressEvent().
event() QEvent, . QEvent::type() .

event(), . . . .
,
. QPaintEvent ,
.
paintEvent().

mousePressEvent(), mouseMoveEvent(),
mouseReleaseEvent() mouseDoubleClickEvent(). globalX(), globalY(), x(), y(), pos()
globalPos().

keyPressEvent()
keyReleaseEvent(). keyPressEvent() , . keyReleaseEvent() .
(),
.

15


, , .

, , ,
. Qt
,
, ,
/ . QObject::installEventFilter(),
, .
, ,
. ,
( ), .
,
. , .
, , ,
- ,
. , , QObject . , . . , .
,
, ,
, .


, QObject eventFilter(). ,
, . : , , .
true, ,
, false ,
, .

15.

231

, . 15.1, ,
. ,
.

. 15.1. ,

15.1. main.cpp

#include <QtGui>
#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");
lbl.installEventFilter(new MouseFilter(&lbl));
lbl.show();
QPushButton cmd("QPushButton");
cmd.installEventFilter(new MouseFilter(&cmd));
cmd.show();
return app.exec();
}

main(), 15.1, : QLineEdit, QLabel


QPushButton. installEventFilter()
, . , .

.
15.2. MouseFilter.h

#ifndef _MouseFilter_h_
#define _MouseFilter_h_

232

III.

#include <QObject>
// ======================================================================
class MouseFilter : public QObject {
protected:
virtual bool eventFilter(QObject*, QEvent*);
public:
MouseFilter(QObject* pobj = 0);
};

15.2 eventFilter(),
, , . ,
, .
15.3. MouseFilter.cpp

#include <QtGui>
#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.3 eventFilter() QEvent::MouseButtonPress,


. ,
QMouseEvent.
button() QMouseEvent, ,
. , , true .
false .

15.

233

, .
, . . ,
.
installFilter() QCoreApplication QApplication(). , . . . , , . .
. QCoreApplication::notify() .

. Qt
,
. . , QObject
eventFilter().

16


.
.

, . , , .

QCoreApplication sendEvent() postEvent(). , , . , sendEvent() ,
. . ,
postEvent() .
,
<A> <Z> (. 16.1).

. 16.1. ,

16.1. main.cpp

#include <QtGui>
int main (int argc, char** argv)
{
QApplication app (argc, argv);
QLineEdit txt("User input: ");
txt.show();
txt.resize(280, 20);
int i;
for (i = 0; i < Qt::Key_Z Qt::Key_A + 1; ++i) {
QChar ch
= 65 + i;

16.

235

int
nKey
= Qt::Key_A + i;
QKeyEvent* pePress =
new QKeyEvent(QEvent::KeyPress, nKey, Qt::NoModifier, ch);
QApplication::sendEvent(&txt, pePress);
QKeyEvent* peRelease =
new QKeyEvent(QEvent::KeyRelease, nKey, Qt::NoModifier, ch);
QApplication::sendEvent(&txt, peRelease);
}
return app.exec();
}

, 16.1, txt QLineEdit, .


QKeyEvent. , ,
( QEvent::KeyPress).
, KeyPress KeyRelease ( )
, , , QLineEdit .
. -,
, Qt::NoModifier , - (. . 14.1). , ASCII- (
65, "A", ).
- , , 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);
}
}

III.

236

mousePress() , , ,
.
, .
, QmouseEvent,
( pwgt) postEvent().
. .
15.
. , , .
<Z> <A> (. 16.2). , <Z> A
. , , .

. 16.2. ,

16.3. main.cpp

#include <QtGui>
#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.3 QLineEdit show()


pFilter, txt.
installEventFilter().

16.

237

16.4. KeyFilter.h

#ifndef _KeyFilter_h_
#define _KeyFilter_h_
#include <QtGui>
// ======================================================================
class KeyFilter : public QObject {
protected:
bool eventFilter(QObject* pobj, QEvent* pe)
{
if (pe->type() == QEvent::KeyPress) {
if (((QKeyEvent*)pe)->key() == Qt::Key_Z) {
QKeyEvent* pe = new QKeyEvent(QEvent::KeyPress,
Qt::Key_A,
Qt::NoModifier,
"A"
);
QApplication::sendEvent(pobj, pe);
return true;
}
}
return false;
}
public:
KeyFilter(QObject* pobj = 0)
: QObject(pobj)
{
}
};
#endif //_KeyFilter_h_

16.4 eventFilter()
QEvent::KeyPress, . QKeyEvent,
key(),
. <A>.
true, , . , eventFilter(), , false, , ,
.

.
QApplication::sendEvent() QApplication::
postEvent(). .

238

III.

IV


, .

17.

18.

19.

20.

21.

22.

23.

OpenGL

24.

25.

26.

27.

28.

17




. . " "

.
, 70% ,
.
, , , , .


. , .

: QPoint QPointF.
X Y, X , Y . , Qt , Y
(. 17.1). QPoint ,
QPointF . , ,
, . /
/ X Y. , . 17.1,
: pt1 pt2.
QPoint pt1(10, 20);
QPoint pt2(20, 10);
QPoint pt3; //(0, 0)
pt3 = pt1 + pt2;

. :
QPoint pt(10, 20);
pt *= 2; // pt = (20, 40)

IV.

242

. 17.1.

(X, Y) x() y() . setX() setY().


, . :
QPoint pt(10, 20);
pt.rx() += 10; // pt = (20, 20)

== () != (
). :
QPoint pt1(10, 20);
QPoint pt2(10, 20);
bool b = (pt1 == pt2); // b = true

, X Y ,
isNull(). :
QPoint pt; // (0, 0)
bool b = pt.isNull(); // b = true

manhattanLength() X Y. :
QPoint pt(10, 20);
int n = pt.manhattanLength(); // n = 10 + 20 = 30

X 2 Y 2 . , .


QSize QSizeF .
. QPoint, . . , / /.
QSize QSizeF, QPoint, QPointF,
==, != isNull(), true ,
.

17.

243

width() height().
setWidth() 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, size1, size2 size3
:
QSize size1(320, 240);
size1.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.

IV.

244

QRect QRectF
( ) .
, , ( ) . ,
. 17.3, :
QPoint pt(10, 10);
QSize size(20, 10);
QRect r(pt, size);

X Y
x() y() .
setX() setY().
size(), QSize.
, width()
height(). setSize(), setWidth() setHeight().

. 17.3.

. 17.4.


QLine QLineF , ,
.
x1() 1(), x2() y2(). p1() p2(),
QPoint/QPointF, . dx() dy() X Y . ,
. 17.4, :
QLine line(10, 10, 30, 20);

QLine QLineF ==, != isNull(),


true ,
.

17.

245

( ) , ,
. 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 and Key
color , , "" ) HSV (Hue, Saturation, Value
, , ).

Qolor
QColor RGB HSV.
QColor. QColor == !=, .

IV.

246

RGB
, , .
RGB (Red, Green, Blue , , ).
, 255 (. 17.6) ( ).

. 17.6. RGB

. 17.6, .
, , . ,
.
0 255 ( 0 1 ), 0 , 255
.
"", . . . , , , .
RGB Qolor
. QColor , .
, ,
, . :
QColor colorBlue(0, 0, 255, 128);

QColor red(),
green(), blue() alpha() . . : redF(), greenF(), blueF() alphaF(). -

17.

247

getRgb(), , :
QColor color(100, 200, 0);
int r, g, b;
color.getRgb(&r, &g, &b);

RGB , , ,
, set ( get, ),
. QRgb, 32- .
qRgb() qRgba(),
, . QRgb
32- . , :
QRgb rgbBlue1 = qRgba(0, 0, 255, 255); //
QRgb rgbBlue2 = qRgb(0, 0, 255);
QRgb rgbBlue3 = 0x000000FF;

qRed(), qGreen(), qBlue() qAlpha() .


QRgb QColor setRgb():
QRgb rgbBlue = 0x000000FF;
QColor colorBlue1(rgbBlue);
QColor colorBlue2;
colorBlue2.setRgb(rgbBlue);

QRgb QColor
rgb().
, , :
QColor colorBlue1("#0000FF");
QColor colorBlue2;
colorBlue2.setNameColor("#0000FF");

HSV
HSV (Hue, Saturation, Value , , )
, RGB,
. , , .
,
Hexcone (. 17.7). :
(Hue) "" , :

, , . ., , 0 360 ;
(Saturation) . -

0 255. , 255 , -

IV.

248

, .
, , 128
0.5 , ;
(Value) . -

, . 0 255 ( 0
1 ).

. 17.7. HSV

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 , , , "" ) .

17.

249

, RGB, 255 (. 17.8)


.
RGB, "", . . . ,
, .
, : , . , . (Key color) .

, Key color, Black. Black
"B"
(Blue), RGB.

. 17.8. CMYK

CMYK ,
RGB HSV. QColor getCmyk() getCmykF() , setCmyk() setCmykF() .

( 256)
. . . . 17.9 ,
RGB(200, 75, 13), 3.

IV.

250

. 17.9. ,


. 17.1 , Qt. , 17 . ,
, ,
, .

19. , ,
Qt::color0 Qt::color1 .
17.1. GlobalColor Qt

RGB-

black

(0, 0, 0)

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)

17.

251
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(), , . , . RGB HSV "" (Value) (


darker() ) ( ), ,
RGB.
:
QColor color = QColor(Qt::red).darker(160);

,
.
Qt , .
QPoint/QPointF X Y, . 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.

. 18.1.

253

. 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).

IV.

254

. 18.3. QPainter

18.1. QPainter

QPainter painter1;
QPainter painter2;
painter1.begin(this);
//
painter1.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.

255

QPainter::save(),
, QPainter::restore().



Qt. .

. , . QPainter::setPen(), QPen. , . 18.1.


18.1. PenStyle Qt

NoPen

SolidLine

DashLine

DotLine

DashDotLine

DashDotDotLine

( = 4)

QPen::setWidth(). , , ,

, .
, ,
NoPen. , ? , , ,
.
QPen::setColor(), QColor. ,
"". QPainter setPen().
QPainter painter(this);
painter.setPen(QPen(Qt::red, 3, Qt::DashLine));

setCapStyle(), Qt::FlatCap ( ), Qt::SquareCap (


) Qt::RoundCap ( ).

setJoinStyle(), Qt::MiterJoin ( -

IV.

256

), Qt::BevelJoin ( ) Qt::RoundJoin
( ). .

, ,
. QBrush QBrush.
.
QPainter::setBrush(),
QBrush , . 18.2.
, QPainter::setBrush() NoBrush.
18.2. rushStyle Qt ()

NoBrush

VerPattern

10

SolidPattern

CrossPattern

11

Dense1Pattern

BDiagPattern

12

Dense2Pattern

FDiagPattern

13

Dense3Pattern

DiagCrossPattern

14

Dense4Pattern

LinearGradientPattern

15

Dense5Pattern

RadialGradientPattern

16

Dense6Pattern

ConicalGradientPattern

17

Dense7Pattern

TexturePattern

24

HorPattern

:
QPainter painter(this);
painter.setBrush(QBrush(Qt::red, Qt::HorPattern));

. 18.2 , TexturePattern.
setTexture() .
:
QPixmap pix("fruits.jpg");
painter.setBrush(QBrush(Qt::black, pix));
painter.drawEllipse(0, 0, 300, 150);

, . 18.4, .

18.

257

. 18.4.

. , .
. Qt :
(linear), (conical) (radial).
QLinearGradient.
(color stops) ,
. 18.3 . 18.5 .
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());

.
0 1, 0 , 1 . .
(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);

IV.

258
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).
, , ,
. ,
(. 18.8).
.
QPainter setRenderHint():
painter.setRenderHint(QPainter::Antialiasing, true);

18.

259

. 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.setPen(QPen(Qt::black, 3));

IV.

260
int n = 8;
for (int i = 0; i < n; ++i) {
qreal fAngle = 2 * 3.14 * i / n;
qreal x
= 50 + cos(fAngle) * 40;
qreal y
= 50 + sin(fAngle) * 40;
painter.drawPoint(QPointF(x, y));
}

. 18.9.

. 18.10.

. 18.11.



drawLine(), (x1, y1) (x2, y2)
QPointF ( 18.7, . 18.10).
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. drawPolyline()

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 y
= 50 + sin(fAngle) * 40;
a[i] = QPointF(x, y);
}
painter.drawPolyline(a, n);

18.

261


, . Qt : fillRect() eraseRect().
. fillRect() .
(x, y) (, ) .
.
eraseRect() ,
. , .
, fillRect()
, paletteBackgroundColor(). 18.9
fillRect() eraseRect(), . 18.12.
18.9. fillRect() eraseRect()

QPainter painter(this);
QBrush brush(Qt::red, Qt::Dense4Pattern);
painter.fillRect(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.
drawRect() . : (X, Y) , .
QRect ( 18.10, . 18.13).
18.10. drawRect()

QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true);

IV.

262
painter.setBrush(QBrush(Qt::red, Qt::DiagCrossPattern));
painter.setPen(QPen(Qt::blue, 3, Qt::DashLine));
painter.drawRect(QRect(10, 10, 110, 70));

drawRoundRect() .
. , X Y
. , 100 .
QRect ( 18.11, . 18.14).
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.
c

. 18.15.

drawEllipse() , ( 18.12, . 18.15).


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));

drawChord() . , ,
. , . .
()
. . , ( 18.13, . 18.16).

18.

. 18.16.

. 18.17.

263

. 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);

.
. drawPie() .
( 18.14, . 18.17).
.
18.14. drawPie()

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.15, . 18.18).


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 y
= 50 + sin(fAngle) * 40;
polygon << QPointF(x, y);
}
painter.drawPolygon(polygon);

264

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")) {
qDebug() << "can not save the file";
}

18.17 . drawPicture(). , , QPicture.


18.17.

QPicture pic;
if (!pic.load("myline.dat")) {
qDebug() << "can not load the file";
}
QPainter painter;
painter.begin(this)
painter.drawPicture(QPoint(0, 0), pic);
painter.end()


QPainter . , , (. 18.19).
. .
QPainter : translate(), scale(), rotate() shear().

18.

265

,
. , ,
, , .

. 18.19.

QPainter Qt
save() restore().
QPainter. save(), .
restore() QPainter . :
pPainter->save();
pPainter->translate(20, 40);
pPainter->restore();

. QPainter
translate(), .
X, Y. , .
,
. ,
20 10 :
QPainter painter;
...
painter.translate(20, 10);

266

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::setMatrix().
, ,
QPainter , . :
QMatrix mat;
mat.scale(0.7, 0.5);
mat.shear(0.2, 0.5);
mat.rotate(15);
painter.setMatrix(mat);
painter.drawText(rect(), Qt::AlignCenter, "Transformed Text");

33:
M11 M12 0
M21 M22 0
Dx Dy 0

18.

267

,
M11, M12, M21, M22, Dx Dy,
QMatrix . . 18.3
. , QPainter translate(20, 10):
QMatrix mat(1, 0, 0, 1, 20, 10);
painter.setMatrix(mat);
18.3.

M11

cos()

M12

sin()

M21

-sin()

M22

cos()

Dx

Dy

(painter path)
: , .
, , ,
, QPainter::drawPath(). . 18.20 , : ,
. 18.18.
18.18.

QPainterPath path;
QPointF
pt1(width(), height() / 2);
QPointF
pt2(width() / 2, -height());
QPointF
pt3(width() / 2, 2 * height());
QPointF
pt4(0, height() / 2);
path.moveTo(pt1);
path.cubicTo(pt2, pt3, pt4);
QRect rect(width() / 4, height() / 4, width() / 2, height() / 2);
path.addRect(rect);
path.addEllipse(rect);

IV.

268
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::setClipRegion()
QPainter::setClipPath().
setClipRegion() QRegion.
. ,
(10, 10),
, 100:
QRegion region(10, 10, 100, 100);

18.

269

, , :
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():
unitd() , -

;
intersected() ,

;
subtracted() ,

;
xored() , , -

.
:
QRegion region1(10, 10, 100, 100);
QRegion region2(10, 10, 100, 100, QRegion::Ellipse);
QRegion region3 = region1.subtract(region2);
painter.setClipRegion(region3);

(composition mode)
,
. .
, , ,
. . 18.22.
QPainter::setCompositionMode().
" " QPainter::CompositionMode
_SourceOver.
, - , ,
.
18.20. main.cpp. lbl()

QLabel* lbl(const QPainter::CompositionMode& mode)


{
QLabel* plbl = new QLabel;
plbl->setFixedSize(100, 100);

IV.

270
QRect
rect(plbl->contentsRect());
QPainter painter;

QImage sourceImage(rect.size(), QImage::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();
QImage resultImage(rect.size(), QImage::Format_ARGB32_Premultiplied);
painter.begin(&resultImage);
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.drawImage(rect, sourceImage);
painter.end();
plbl->setPixmap(QPixmap::fromImage(resultImage));
return plbl;
}

. 18.22.

lbl(), 18.20,
,
. setFixedSize() ,

18.

271

rect.
(sourceImage) (resultImage) . , QPainter::drawPolygon(), , .
QPainter::drawEllipse() , . QPainter::setCompositeMode() ,
lbl() mode, (sourceImage)
QPainter::drawImage().
QLabel::setPixmap()
. .
18.21. main.cpp. main()

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);
wgt.setLayout(pgrd);
wgt.show();
return app.exec();
}

IV.

272

, 18.21, ( lbl()) , . (layout) (pgrd) (wgt).


,
QGraphicsItem (. 21).
setGraphicsEffect().
QGraphicsEffect. : (blur),
(colorization), (drop shadow) (opacity). , QGraphicsEffect
(. 18.23).
,
, QGraphicsEffect
draw(), , . QPainter,
.
,
(. 22).
, . 18.24.
18.22. main.cpp. lbl()

QLabel* lbl(QGraphicsEffect* pge)


{
QLabel* plbl = new QLabel;
plbl->setPixmap(QPixmap("happyos.png"));
if (pge) {
plbl->setGraphicsEffect(pge);
}
return plbl;
}

lbl(), 18.22, . ,
setGraphicsEffect(). , , .
.
18.23. main.cpp. main()

int main(int argc, char** argv)


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

18.

273

QGraphicsBlurEffect*
pBlur
= new QGraphicsBlurEffect;
QGraphicsDropShadowEffect* pShadow
= new QGraphicsDropShadowEffect;
QGraphicsColorizeEffect*
pColorize = new QGraphicsColorizeEffect;
//Layout Setup
QFormLayout* pform = new QFormLayout;
pform->addRow("No Effects", lbl(0));
pform->addRow("Blur", lbl(pBlur));
pform->addRow("Drop Shadow", lbl(pShadow));
pform->addRow("Colorize", lbl(pColorize));
wgt.setLayout(pform);
wgt.show();
return app.exec();
}

. 18.23.

. 18.24.
: (Blur),
(Drop Shadow) (Colorization)

274

IV.

, 18.23,
( pBlur, pShadow pColorize).
QFormLayout , .

QPainter ,
QPaintDevice. QPainter , ,
, , (. 20) . QPainter
. , . .
QPainter , , . .
QPicture, , ,
.
,
. ,
Qt, .
Qt : , .
.
, .
QPainter ,
, , .
.
QRegion , .
,
.

.
, QGraphicsEffect,
.

19

, . "", .
,
, .


,
. Qt : PNG, BMP, XBM, XPM, PNM,
JPEG, MNG, GIF, PNM, PBM, PGM PPM. .
!

, ,
. , Windows
qgif4.dll, qico4.dll, qjpeg4.dll, qtiff4.dll
<MyApplication>/imageformats/. Linux , Mac OS X
"macdeployqt", .
.

BMP
BMP (. Bit map) Windows ,
. . BMP (API) Windows. BMP
, Qt .

IV.

276

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 .,
. ,
, , , , . .
.

XPM
XPM (XPixMap) X11 (UNIX) .
, , XMP-
, .
.
24- .

, , . Qt,
(. 3) , . . -

19.

277

, , , PNG JPEG.

. 19.1 XPM,
C, , XPM (),
().

. 19.1. XPM

/*XPM*/, .
image_xpm, .

( 1616 ). ( 4). . , #, RGB (
HTML). c,
color ().

c s, . , , None,
.

. 19.1 ,
, - , - @.
.

IV.

278

-
-
, , ,
. ,
,

.

QImage
QImage - . QPaintDevice,
, QPainter.
QImage , . 19.1.
19.1. Format QImage

Format_Invalid

Format_Mono

.
,

Format_MonoLSB

.
,

Format_Index8

8-
(. 17)

Format_RGB32

.
- 0xFF, . .

Format_ARGB32

32

Format_ARGB32_Premultiplied

Format_ARGB32, QImage

format(). convertToFormat(), QImage.


, ,
. ,
320 200 32 .
QImage img(320, 240, QImage::Format_RGB32);

QImage , , QImage. Qt,


, . :
QImage img("lisa.jpg");

19.

279

XPM. ,
. 19.1, :
#include "image_xpm.h"
...
QImage img(image_xpm);

load() .
, . , .
unsigned char*, : GIF, BMP, JPG, XPM, XBM PNG.
, QImage
. :
QImage img;
img.load("lisa.jpg");

save()
QImage . , ,
. :
QImage img(320, 240, 32, QColor::blue);
img.save("blue.jpg", "JPG");


, Unisys LZW,
GIF, GIF
. Qt
GIF.

QImage ,
. RGB- (X, Y)
pixel(x, y). RGB-
QRgb (. 17). :
QRgb rgb = img.pixel(250, 100);


pixelIndex() (. 17)
(X, Y). ,
8 .

(X, Y) RGB-
setPixel(x, y, rgb).

, 8 , rgb (. 17),
setColor().

:
QRgb rgb = qRgb(200, 100, 0);
img.setPixel(20, 50, rgb);

IV.

280

QImage ,
.

(. . 19.1).
, , , .
QImage , .

scanLine() ,
, . , 0 , .
brightness(), .
. 19.2.

. 19.2. /

19.1. brightness()

QImage brightness(const QImage& imgOrig, int n)


{
QImage imgTemp = imgOrig;
qint32 nHeight = imgTemp.height();
qint32 nWidth = imgTemp.width();
for (qint32 y = 0; y < nHeight; ++y) {
QRgb* tempLine = reinterpret_cast<QRgb*>(imgTemp.scanLine(y));
for (qint32 x = 0; x < nWidth; ++x) {
int r = qRed(*tempLine) + n;
int g = qGreen(*tempLine) + n;
int b = qBlue(*tempLine) + n;
int a = qAlpha(*tempLine);
*tempLine++ = qRgba(r > 255 ? 255 : r < 0 ? 0 : r,
g > 255 ? 255 : g < 0 ? 0 : g,
b > 255 ? 255 : b < 0 ? 0 : b,
a
);

19.

281

}
}
return imgTemp;
}

brightness() (. 19.1) , , . (
imgTemp). .
width() height(). 0 height().
scanLine() tempLine.
width(). , qRed(), qGreen(), qBlue()
RGB ( n). - .
r, g, b a. , (tempLine), QRgb,
qRgba() ,
0 255. ,
. imgTemp.
19.2. main()

int main(int argc, char** argv)


{
QApplication app(argc, argv);
QImage
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::fromImage(brightness(img, i)));
phbx->addWidget(plbl);
}
wgt.setLayout(phbx);
wgt.show();
return app.exec();
}

( 19.2)
happyos.png , . -

IV.

282

setPixmap() ,
brightness() .
addWidget().
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) 110, 100 (. 19.4).
19.4.

QPainter painter(this);
QImage
img("lisa.jpg");
painter.drawImage(0, 0, img, 30, 30, 110, 100);

invertPixels() QImage::InvertRgb, . QImage::InvertRgba -

19.

283

, -. 19.5
, . 19.5.
19.5.

QPainter painter(this);
QImage img("lisa.jpg");
painter.drawImage(0, 0, img);
img.invertPixels(QImage::InvertRgb);
painter.drawImage(img.width(), 0, img);

. 19.5.

scaled() . Qt::IgnoreAspectRatio Qt::KeepAspectRatio, , 17. 19.6 , . 19.6.


19.6.

QPainter painter(this);
QImage img1("lisa.jpg");
painter.drawImage(0, 0, img1);
QImage img2 =
img1.scaled(img1.width() / 2, img1.height(), Qt::IgnoreAspectRatio);
painter.drawImage(img1.width(), 0, img2);
QImage img3 =
img1.scaled(img1.width(), img1.height() / 2, Qt::IgnoreAspectRatio);

IV.

284
painter.drawImage(0, img1.height(), img3);

QImage img4 =
img1.scaled(img1.width() / 2, img1.height(), Qt::KeepAspectRatio);
painter.drawImage(img1.width(), img1.height(), img4);

. 19.6.

QImage
. mirrored()
, .
mirrored() , ,
. 19.7 , .
. 19.7.
19.7.

QPainter painter(this);
QImage img("lisa.jpg");
painter.drawImage(0, 0, img);
painter.drawImage(img.width(), 0, img.mirrored(true, true));

19.

285

. 19.7.

QImage
, QImage . , . QImage
32-,
. . QImage::Format_ARGB32 QImage::FormatARGB32_Premultiplied. QImage::
FormatARGB32_Premultiplied , . .
. 19.8.
. 19.8 .

. 19.8.

IV.

286
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.drawEllipse(0, 0, size().width(), size().height());
painter.end();
painter.begin(this);
painter.drawImage(0, 0, img);
painter.end();
}

19.8, paintEvent()
QImage , size().
QPainter begin() QImage
. initFrom()
, , , . . setRenderHint()
QPainter::Antialiasing; true , (false , ).
eraseRect() , .
, rect().
drawEllipse(). end()
QImage. ,
.
begin(). , drawImage() QImage
.

-
- , -, . . . - QPainter.
, , , , .

QPixmap
QPaintDevice. QPixmap. ,

19.

287

.
, . ., ,
QPixmap, ,
QPainter, .
.
:
QPixmap pix(320, 240);

QPixmap
.
QPixmap::defaultDepth(). . :
QPixmap pix("forest.jpg");

QPixmap, QImage, XPM


:
#include "image_xpm.h"
...
QPixmap pix(image_xpm);

QPixmap , , . .
QImage.
QPainter
load() save().
QImage ( ).

QPixmap
QPainter::drawPixmap(). 19.9
drawPixmap(). ,
. , . . 19.9.
19.9.

QPainter painter(this);
QPixmap pix("forest.jpg");
painter.drawPixmap(0, 0, pix);
QRect r(pix.width(), 0, pix.width() / 2, pix.height());
painter.drawPixmap(r, pix);

QPixmapCache
QPixmap.
, .
insert() QPixmap .

IV.

288

. 19.9. QPixmap

, . - find(), . ,
, , .

QBitmap
QBitmap QPixmap QBitmap.
, , . ,
Qt::color0 Qt::color1. (bi-level).
.

QPixmap
QPixmap ,
QPixmap::setMask().
, , .
QBitmap.
QPainter, color0,
color1. , . , . . . . 19.10
, ,
.

19.

289

. 19.10.

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(&bmp);
painter.setPen(QPen(Qt::color1));
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();

19.10 paintEvent(). QPixmap,


( size()).
pix begin(). drawPixmap()
pix stein.jpg, end().
bmp,
. fill()
Qt::color0 ( ). , Qt::color1, , , ,
, . pix setMask(),
.

IV.

290


QWidget, QPixmap, setMask().
, . ( 19.11), . 19.11.

. 19.11.

19.11. main.cpp. main()

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();
}

19.11 Window. pix


. setPixmap() ,
, Window QLabel.
, GIF, PNG XMP, . load() ,
setMask().

19.

291

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)
{
}
};

, QLabel Qt::FramelessHint.
. Window (. 19.12) mousePressEvent() mouseMoveEvent(),
, . m_ptPosition .
,
: QPixmap createHeuristicMask(),
, .
.
, . ,
.
,
. . setAttribute()
Qt::WA_TranslucentBackground. ( 19.13),
. 19.12. .
.
. 19.12.

IV.

292
19.13. main.cpp. Window

int main(int argc, char** argv)


{
QApplication app(argc, argv);
QLabel
lbl;
lbl.setWindowFlags(Qt::Window | Qt::FramelessWindowHint);
lbl.setAttribute(Qt::WA_TranslucentBackground);
lbl.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(1);
lbl.setLayout(pvbx);
lbl.show();
return app.exec();
}

(lbl) ,
.
Qt::WA_TranslucentBackground. ,
, .
, 16 16 ,
, clicked()
QCoreApplicaion::quit() app. ( pvbx).

Qt . , BMP, GIF, PNG, JPEG XPM. XPM . XPM XBM


, C.
Qt -
-.
- QImage.
QImage , ,
.
,

19.

293

. QImage , , : , , . QPainter QImage , , . .


- QPixmap.
QImage.
QPixmap QPainter.
, . QPixmap QBitmap .

20


, ,
, , ,
, .
" "

. ,
. . ,
. ,
. ().
( ). . . , .
.
Qt QFont .
:
;
;
;
;
.

QFont QWidget::setFont()
, .
, QFont
QApplication::setFont().
Qt : QFontDataBase, QFontInfo
QFontMetrics.
QFontDatabase

. families(),
QStringList. QFontDatabase
styleString() QFontInfo.

20.

295

QFontInfo .

family() . italic() bold() , ( ) .


QFontMetrics ,

. 20.1.

. 20.1.

QFontMetrics QFont, . leftBearing() rightBearing() . lineSpacing() . width(const QString&, int len) , ; ,


. width(). height(). :
QFontMetrics fm(QFont("Courier", 18, QFont::Bold));
QString
str = "String";
qDebug() << "Widht:" << fm.width(str)
<< "Height:" << fm.height();


ascent() descent() . ( ),
,
.
boundingRect() , QRect,
, .

IV.

296


QPainter QPainter::setFont()
QFont. QPainter 7 drawText() , :
drawText(int x, int y, const QString& str) psz.

x, y .
drawText(const QPoint& pt, const QString& psz, int nLen = -1) -

, x y
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");

. 20.2.

QPainter
drawText():drawText(const QRect& r, int flags, const QString& str)
str r . C flags . , . 7.1 20.1,
| ().
20.1. TextFlag Qt

TextSingleLine

0x0100

( \n)

TextDontClip

0x0200

, ,
,

TextExpandTabs

0x0400

\t

TextShowMnemonic

0x0800

& ,

20.

297
20.1 ()

TextWordWrap

0x1000

20.2 .
. 20.3.
, r,

TextWordWrap. drawRect()
.

. 20.3.

20.2. setFont(), drawRect() drawText()

QPainter painter(this);
QRect r = QRect(0, 0, 120, 200);
painter.setFont(QFont("Times", 25, QFont::Normal));
painter.drawRect(r);
painter.drawText(r, Qt::AlignCenter | Qt::TextWordWrap, "Draw Text");

(. 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);

. 20.4. ,

QPen.
QPainter setPen()
setFont(), drawText():

IV.

298
QPainter painter(this);
painter.setPen(QPen(gradient, 0));
painter.setFont(QFont("Times", 50, QFont::Normal));
painter.drawText(60, 60, "Gradient Text");

, , ,
. , , . , ,
, . elidedText() QFontMetrics. . 20.5 ,
, ,
, .

. 20.5.

20.3. c

#include <QtGui>
// ======================================================================
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.show();
return app.exec();
}

20.

299

20.3 paintEvent() ( str).


elideText(), . .
Qt::ElideMiddle (
. 20.2). , drawText().
. 20.2 , .
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).
: (QGraphicsScene), (QGraphicsView) (QGraphicsItem) (. 21.1 21.3).

. 21.1.

: QGraphicsScene
,
QGraphicsItem, QGraphicsView ,
QAbstractScrollArea.
( QGraphicsScene),
(. 21.2).

21.

301

. 21.2.

(QGraphicsScene) . - ,
QGraphicsScene . , ,
. .
changed() , .
(QGraphicsScene) , , , QGraphicsItem (. . 21.3).
. QGraphicsScene::addItem().
addEllipse(),
addLine(), addPath(), addPixmap(), addPolygon(), addRect() addText(),
, .
, QGraphicScene::items(). , QGraphicScene::itemAt(),
, .
QGraphicsScene
QRectF.
.

QGraphicsView ,
(QGraphicsScene).

302

IV.

(QGraphicsScene)
QGraphicsView. , QGraphicsView
QAbstractScrollArea, , . , QGraphicsScene, . , .
QGraphicsView , . , . . .
,
QGraphicsView::centerOn(), .
, , QGraphicsView
QAbstractScrollArea, ,
(viewport) . QWidget QGLWidget
(. 23)
. QAbstractScrollArea::setViewPort(). ,
, OpenGL, :
pView->setViewport(new QGLWidget);

, setMatrix(),
, .

QGraphicsItem (. . 21.3). , (drag & drop), (collision detection). :


setPos();
hide() show();
/ setEnable();
rotate(), scale(), translate(), shear() setMatrix();
paint().

, . . .
(. 21.3)
, QGraphicsItem
paint() boundingRect().
, QAbstractGraphicsShapeItem,

(QGraphicsEllipseItem),

(QGraphicsPolygonItem), (QGraphicsRectItem) (QgraphicsSimpleTextItem). - , , , QAbstractGraphicsShapeItem.


, . 21.3
. QGraphicsSimpleTextItem QGraphicsTextItem.

21.

303

QGraphicsSimpleTextItem -

. ,
QGraphicsTextItem,
, .

. 21.3.

(GraphicsLineItem), (QGraphicsPixmapItem), (QGraphicsSvgItem). QGraphicsItemGroup .


. 21.4 .
21.1. main.cpp

#include <QtGui>
int main(int argc, char** argv)

IV.

304
{
QApplication
app(argc, argv);
QGraphicsScene scene(QRectF(-100, -100, 300, 300));
QGraphicsView view(&scene);

QGraphicsRectItem* pRectItem = new QGraphicsRectItem(0, &scene);


pRectItem->setPen(QPen(Qt::black));
pRectItem->setBrush(QBrush(Qt::green));
pRectItem->setRect(QRectF(-30, -30, 120, 80));
pRectItem->setFlags(QGraphicsItem::ItemIsMovable);
QGraphicsPixmapItem* pPixmapItem =
scene.addPixmap(QPixmap("haus.jpg"));
pPixmapItem->setFlags(QGraphicsItem::ItemIsMovable);
QGraphicsTextItem* pTextItem =
scene.addText("Move us with your mouse");
pTextItem->setFlags(QGraphicsItem::ItemIsMovable);
QGraphicsLineItem* pLineItem =
scene.addLine(QLineF(-10, -10, -80, -80), QPen(Qt::red, 2));
pLineItem->setFlags(QGraphicsItem::ItemIsMovable);
view.show();
return app.exec();
}

. 21.4. ,

21.1 app QGraphicsScene


QGraphicsView. view scene,
QGraphicsView::setScene().
( pRectItem)
QGraphicsScene, .

21.

305

QGraphicsScene::addItem(). setPen()
. , , setBrush(). setRect() . QGraphicsScene::
addPixmap(), QGraphicsScene::addText() QGraphicsScene::addLine()
, .
, setFlags() QGraphicsItem::
ItemIsMoveable.
, show()
.
, , , . - , :
QGraphicsLineItem* pLineItem =
scene.addLine(QLineF(-10, -10, -80, -80), QPen(Qt::red, 2));
QGraphicsTextItem* pTextItem = scene.addText("Child");
pTextItem->setParentItem(pLineItem);

,
, . . , :
QGraphicsTextItem* pTextItem = scene.addText("Shear");
pTextItem->shear(-0.5, 0.0);

,
.
QGraphicsItem .
QGraphics::shape() QGraphicsItem::
collidesWith(). ,
QGraphicsItem::shape(). . QGraphicsItem
.

, .
QGraphicsView QAbstractScrollArea, . ,
. ,
. , ,
QGraphicsView::scene(), , , .
- , . , .
. :

IV.

306

, ,
, .
, ,
. . . 21.5
, .

. 21.5.

, , ,
(QGraphicsHoverEvent) (QGraphicsContextMenuEvent).
(drag & drop).
, ,
setAcceptDrops(). dragEnterEvent(), dragMoveEvent(), dragLeaveEvent() dropEvent().
, QDrag, , .
, - . , QGraphicsSceneEvent::widget().
.
, . 21.6. :
;
;
;
.
21.2. MyView.h

#ifndef _MyView_h_
#define _MyView_h_
#include <QGraphicsView>

21.

307

// ======================================================================
class MyView: public QGraphicsView {
Q_OBJECT
public:
MyView(QGraphicsScene* pScene, QWidget* pwgt = 0)
: QGraphicsView(pScene, pwgt)
{
}
public slots:
void slotZoomIn()
{
scale(1.1, 1.1);
}
void slotZoomOut()
{
scale(1 / 1.1, 1 / 1.1);
}
void slotRotateLeft()
{
rotate(-5);
}
void slotRotateRight()
{
rotate(5);
}
};
#endif

//_MyView_h_

21.2 MyView,
QGraphicsView. MyView ,
, (. 21.4).
21.3. main.cpp. SimpleItem

class SimpleItem : 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);
}

IV.

308
virtual void paint(QPainter* ppainter,
const QStyleOptionGraphicsItem*,
QWidget*
)
{
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::mousePressEvent(pe);
}
virtual void mouseReleaseEvent(QGraphicsSceneMouseEvent* pe)
{
QApplication::restoreOverrideCursor();
QGraphicsItem::mouseReleaseEvent(pe);
}
};

. 21.6. ,

21.

309

SimpleItem, 21.3, . boundingRect() , .


, , (penWidth).
paint() . , 3 .
QPainter setPen(), save(),
restore().
mousePressEvent(), , , ,
mousePressEvent()
.
mouseReleaseEvent() . mouseReleseEvent() .
21.4. main.cpp. main()

int main(int argc,


{
QApplication
QWidget
QGraphicsScene
MyView*
QPushButton*
QPushButton*
QPushButton*
QPushButton*

char** argv)
app(argc, argv);
wgt;
scene(QRectF(-100, -100, 640, 480));

pView
pcmdZoomIn
pcmdZoomOut
pcmdRotateLeft
pcmdRotateRight

=
=
=
=
=

new
new
new
new
new

MyView(&scene);
QPushButton("&Zoom In");
QPushButton("Z&oom Out");
QPushButton("&Rotate Left");
QPushButton("Ro&tate Right");

pView->setRenderHint(QPainter::Antialiasing, true);
SimpleItem* pSimpleItem = new SimpleItem;
scene.addItem(pSimpleItem);
pSimpleItem->setPos(0, 0);
pSimpleItem->setFlags(QGraphicsItem::ItemIsMovable);
QGraphicsPixmapItem* pPixmapItem =
scene.addPixmap(QPixmap("haus2.jpg"));
pPixmapItem->setParentItem(pSimpleItem);
pPixmapItem->setFlags(QGraphicsItem::ItemIsMovable);
QObject::connect(pcmdZoomIn, SIGNAL(clicked()),
pView,
SLOT(slotZoomIn())
);

IV.

310
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(pcmdZoomIn);
pvbxLayout->addWidget(pcmdZoomOut);
pvbxLayout->addWidget(pcmdRotateLeft);
pvbxLayout->addWidget(pcmdRotateRight);
wgt.setLayout(pvbxLayout);
wgt.show();
return app.exec();
}

main(), 21.4, (scene), ( pView), ( pSimpleItem pPixmapItem) ,


( pcmdRotateLeft pcmdRotateRight),
( pcmdZoomIn pcmdZoomOut).
setRenderHint() , ( ).
SimpleItem
QGraphicsScene::addItem(), setPos() .
,
setFlags() QGraphicsItem::ItemIsMovable.
( pPixmapItem)
setParent() , , SimpleItem. setFlags()
. , , "-". , ,
, , ,
, . . .

MyView, QVBoxLayout
wgt.

21.

311


QGraphicsScene , , ,
. , ,
, , c ,
.
.
(. 21.7).

. 21.7.

21.5. . main.cpp

#include <QtGui>
int main(int argc,
{
QApplication
QGraphicsScene
QGraphicsView

char** argv)
app(argc, argv);
scene(QRectF(0, 0, 400, 400));
view(&scene);

QPushButton cmd("Quit");
QGraphicsProxyWidget* pproxyWidget = scene.addWidget(&cmd);
QTransform
transform
= pproxyWidget->transform();

IV.

312

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)),
&prb, SLOT(setValue(int))
);
view.rotate(15);
view.show();
return app.exec();
}

( 21.5) (scene) (view). Quit


addWidget(), QGraphicsProxyWidget.
,
QTransform. translate(), rotate() scale(). rotate():
,
, Y (Qt::YAxis).
( pproxyWidget) setTransform(). QDial QProgressBar. - , , , Quit quit(),
valueChanged() QDial setValue() QProgressBar. 15 Z.

21.

313

, , , .

,
,
. QGraphicsScene, QGraphicsView, QGraphicsItem
, . "". QGraphicsScene
QGraphicsView.
QGraphicsScene , . , . . ,
.
, QGraphicsItem, , , , . . . (QGraphicsItem)
QGraphicsScene.

22

.
" ". , "" .
, . ,

QMovie
QPixmap,
. QMovie,
.
QPixmap QImage.
MNG GIF. , , , 28, Phonon, , .
QMovie . .
.
: setPaused(bool),
setSpeed(), stop() start().
setPaused() true ,
false .
stateChanged() . QMovie::start() , stop() .
state(), :
QMovie::Paused , ;
QMovie::Running , ;
QMovie::NoRunning .

22.

315

,
frameCount(). ,
currentPixmap() currentImage(),
QPixmap QImage.
QLabel. QLabel
setMovie(), .
, . 22.1, .

. 22.1.

22.1. main.cpp

#include <QtGui>
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QLabel
lbl;
QMovie
mov("motion.mng");
lbl.setMovie(&mov);
lbl.resize(328, 270);
lbl.show();
mov.start();
return app.exec();
}

22.1, 3 : ( app),
(lbl) (mov),

IV.

316

motion.mng. setMovie()
. resize() , . . .
( show()) start() .

SVG-
SVG (Scalable Vector Graphics).
2001 W3C (World Wide Web
Consortium).
XML, , .

Web-.
Qt QtSvg. ,
( pro) , QT += svg. SVG-
QSvgWidget. SVG-
QSvgWidget, load(). load() ,
, QByteArray.
QSvgRenderer, , , . QSvgRenderer QImage QGlWidget. . 22.2
QSvgWidget.

. 22.2.

22.2. main.cpp

#include <QtGui>
#include <QtSvg>

22.

317

int main(int argc, char **argv)


{
QApplication app(argc, argv);
QSvgWidget svg(":/motion.svg");
svg.show();
QObject::connect(svg.renderer(), SIGNAL(repaintNeeded()),
&svg,
SLOT(repaint())
);
return app.exec();
}

22.2 QSvgWidget SVG motion.svg, . show(),


. repaintNeeded()
QSvgRenderer repaint() QSvgWidget ,
QSvgWidget.


Qt ,
, , , , ,
. . Qt
, , ,
(. 35).

QTimer, QTimeLine QGraphicsItemAnimation. .
,
,
.
.
GraphicsView. , . 22.3.
QAbstractAnimation , , start(), stop() pause()
, . stateChanged() , . : QVariantAnimation, QAnimationGroup
QPauseAnimation. "Variant" QVariantAnimation ,
, , , ,
.
QVariantAnimation QPropertyAnimation, , .
(. 22.4),
.

IV.

318

. 22.3.

22.3. main.cpp.

#include <QtGui>
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QLabel
lbl;
lbl.setPixmap(QPixmap("happyos.png"));
QGraphicsColorizeEffect effect;
lbl.setGraphicsEffect(&effect);
QPropertyAnimation anim(&effect, "color");
anim.setStartValue(Qt::gray);
anim.setKeyValueAt(0.25f, Qt::green);
anim.setKeyValueAt(0.5f, Qt::blue);
anim.setKeyValueAt(0.75f, Qt::red);
anim.setEndValue(Qt::black);
anim.setDuration(3000);
anim.setLoopCount(-1);
anim.start();
lbl.show();
return app.exec();
}

. 22.4.

22.

319

22.3 QLabel
setPixmap() .
(. 18) setGraphicsEffect().
(anim)
effect, "color", . setStartValue() , setKeyValueAt()
0 1, setEndValue()
.

, . .
.
, ,
.

setDuration()
. 3000 , , 3 .
setLoopCount() ,
, , . , start() .
QAnimationGroup.
. , . .
, QObject. . ,
. , ,
, . ,
, .
, ,
22.4.
22.4.

QParallelAnimationGroup* pgroup1 = new QParallelAnimationGroup;


pgroup1->addAnimation(panim1);
pgroup1->addAnimation(panim2);
QSequentialAnimationGroup* pgroup2 = new QSequentialAnimationGroup;
pgroup2->addAnimation(panim3);
pgroup2->addAnimation(panim4);
pgroup2->addAnimation(panim5);
pgroup2->addAnimation(group1);
...
pgroup2->start();

22.4 ( QParallelAnimationGroup)
addAnimation() : panim1
panim2. ( QSequentialAnimationGroup) , addAnimation()
, . start() .

IV.

320


,
. (Easing Curves) ,
. (. 22.5),
.

. 22.5.

22.5.

#include <QtGui>
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QLabel
lbl1("Animated Window1");
QLabel
lbl2("Animated Window2");
QPropertyAnimation* panim1 =
new QPropertyAnimation(&lbl1, "geometry");
panim1->setDuration(3000);
panim1->setStartValue(QRect(120, 0, 100, 100));
panim1->setEndValue(QRect(480, 380, 200, 200));
panim1->setEasingCurve(QEasingCurve::InOutExpo);
QPropertyAnimation* panim2 = new QPropertyAnimation(&lbl2, "pos");
panim2->setDuration(3000);

22.

321

panim2->setStartValue(QPoint(240, 0));
panim2->setEndValue(QPoint(240, 480));
panim2->setEasingCurve(QEasingCurve::OutBounce);
QParallelAnimationGroup group;
group.addAnimation(panim1);
group.addAnimation(panim2);
group.setLoopCount(3);
group.start();
lbl1.show();
lbl2.show();
return app.exec();
}

22.5 (lbl1 lbl2)


( panim1 panim2).
"geometry" , "pos" . , ( setDuration()).
setStartValue() setEndValue() . QRect, QPoint. setEasingCurve()
. , :
InOutExpo OutBounce. , ,
( group). addAnimation() (
setLoopCount()). , start()
.
. 22.1 , , setEasingCurve() . , QEasingCurve .
22.1.

Linear

OutExpo

InQuad

InOutExpo

IV.

322

22.1 ()

OutQuad

OutInExpo

InOutQuad

InCirc

OutInQuad

OutCirc

InCubic

InOutCirc

OutCubic

OutInCirc

InOutCubic

InElastic

OutInCubic

OutElastic

InQuart

InOutElastic

22.

323
22.1 ()

OutQuart

OutInElastic

InOutQuart

InBack

OutInQuart

OutBack

InQuint

InOutBack

OutQuint

OutInBack

InOutQuint

InBounce

OutInQuint

OutBounce

InSine

InOutBounce

IV.

324

22.1 ()

OutSine

OutInBounce

InOutSine

InCurve

OutInSine

OutCurve

InExpo

SineCurve

CosineCurve


(States) . , .
. , . . . , , . .,
- , .
.
(Transitions). .
Off/On.
Off . Push , . 22.6.

22.

325

. 22.6.

22.6. main.cpp.

#include <QtGui>
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QWidget
wgt;
wgt.setFixedSize(300, 50);
wgt.show();
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.width() / 2;
QStateMachine* psm = new QStateMachine;
QState* pStateOff = new QState(psm);
QRect
rect1(0, 0, nButtonWidth, wgt.height());
pStateOff->assignProperty(pcmd, "geometry", rect1);
pStateOff->assignProperty(plblOff, "visible", true);
pStateOff->assignProperty(plblOn, "visible", false);
psm->setInitialState(pStateOff);

IV.

326

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* ptrans1 =
pStateOff->addTransition(pcmd, SIGNAL(clicked()), pStateOn);
QSignalTransition* ptrans2 =
pStateOn->addTransition(pcmd, SIGNAL(clicked()), pStateOff);
QPropertyAnimation* panim1 =
new QPropertyAnimation(pcmd, "geometry");
ptrans1->addAnimation(panim1);
QPropertyAnimation* panim2 =
new QPropertyAnimation(pcmd, "geometry");
ptrans2->addAnimation(panim2);
psm->start();
return app.exec();
}

22.6 , (wgt), setFixedSize() . ( plblOff plblOn) ( phbx). ,


. :
( QStateMachine),
. , QState, Off
( pStateOff). assignProperty()
. Off
Off , On . setInitialState(), c
pStateOff, .
On assignProperty(), , .
addTransition() ,
, , .
Off On,
, Push.
On, .
addTransction() QSignalTransition,
.
( panim1 panim2) On Off
addAnimation() ( ptrans1 ptrans2).
start().

22.

327

. , .
QMovie,
. setMovie().
SVG
QtSvg, QSvgWidget.
Qt .
, : , , . ., . , ,
.
.
.
, . , , , , .

23

OpenGL
, .
.

, , ,
. . , , ( ), ,
, .
.
OpenGL ,
Silicon Graphics 1992 . ,

. , ,
, . , OpenGL
(Anti-aliasing) . ,
.
OpenGL , , OpenGL-
(rendering
context) . OpenGL " " Qt
- ,
OpenGL- . QtOpenGL OpenGL Qt-. Arthur, QPainter (. 18)
OpenGL. OpenGL
.
OpenGL.

OpenGL
OpenGL -.
, .

23. OpenGL

329

OpenGL gl, GL_. , . ,


glColor3f() , (. 23.1). OpenGL, , *. , : glColor*().
, , ,
glColor.

. 23.1. OpenGL

. 23.1 , OpenGL.
23.1. OpenGL

OpenGL

C++

GLbyte

Char

GLshort

Short

GLint

Int

GLfloat

float

GLdouble

double

ub

GLubyte

unsigned byte

us

GLushort

usnigned short

ui

GLuint

unsigned int

GL_

GLenum

Enum

v , .
, glColor3fv() :
GLfloat a[] = {1.0f, 0.0f, 0.0f}
glColor3fv(a);

IV.

330

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 , , : initializeGL(),
resizeGL() paintGL(). QGLWidget virtual protected.
initializeGL() . , OpenGL. , , QGLWidget, OpenGL.
resizeGL(int width, int height) resizeEvent(). , , QGLWidget. .
paintGL()
paintEvent(). , . , ,
resizeGL().
. 23.2 ,
, .

. 23.2.

23. OpenGL

331

23.1. OGLQuad.pro

TEMPLATE
QT
HEADERS
SOURCES
TARGET

= app
+= opengl
= OGLQuad.h
= OGLQuad.cpp \
main.cpp
= ../OGLQuad

23.1 QT (. 3),
opengl. , QtOpenGL.
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.2, OGLQuad, QGLWidget.


23.3. OGLQuad.h

#ifndef _OGLQuad_h_
#define _OGLQuad_h_
#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);
};
#endif //_OGLQuad_h_

IV.

332

23.3 OGLQuad , QGLWidget,


: initializeGL(), resizeGL() paintGL().
23.4. OGLQuad.cpp. OGLQuad

OGLQuad::OGLQuad(QWidget* pwgt/*= 0*/) : QGLWidget(pwgt)


{
}

, 23.4, , pwgt .
23.5. OGLQuad.cpp. initializeGL()

/*virtual*/void OGLQuad::initializeGL()
{
qglClearColor(Qt::black);
}

23.5 qglClearColor() . Qt QColor OpenGL, .



OpenGL glClearColor(). qglClearColor()
QColor.
23.6. OGLQuad.cpp. resizeGL()

/*virtual*/void OGLQuad::resizeGL(int nWidth, int nHeight)


{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glViewport(0, 0, (GLint)nWidth, (GLint)nHeight);
glOrtho(0, 100, 100, 0, -1, 1);
}

23.6 glMatrixMode()
. , .
glLoadIdentity() .
OpenGL , . (modelview matrix) , (projection matrix)
. , .
resizeGL() , (viewport).
glViewPort() ( ).

23. OpenGL

333

. glOrtho().
, ,
, .
23.7. OGLQuad.cpp. paintGL()

/*virtual*/void OGLQuad::paintGL()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBegin(GL_QUADS);
glColor3f(1, 0, 0);
glVertex2f(0, 100);
glColor3f(0, 1, 0);
glVertex2f(100, 100);
glColor3f(0, 0, 1);
glVertex2f(100, 0);
glColor3f(1, 1, 1);
glVertex2f(0, 0);
glEnd();
}

glClear()
(GL_COLOR_BUFFER_BIT) (GL_DEPTH_BUFFER_BIT).
. , qglColor().
OpenGL . , , .
glBegin().
GL_QUADS , ( 23.7). glColor*() ,
glVertex*()
. glBegin() glEnd().
, , OpenGL
,
. glShadeModel(). GL_FLAT , GL_SMOOTH
.

OpenGL-

QGLWidget QWidget, , .

IV.

334

show() showFullScreen().
,
. , . . ,
, show() showFullScreen().
OpenGL-
.

OpenGL
OpenGL , ,
, , .
. , . 23.3, , .

. 23.3. ,

23.8. main.cpp

#include <QApplication>
#include "OGLDraw.h"
int main(int argc, char** argv)
{
QApplication app(argc, argv);
OGLDraw
oglDraw;
oglDraw.resize(400, 200);
oglDraw.show();
return app.exec();
}

23.8 oglDraw OGLDraw.

23. OpenGL

335

23.9. OGLDraw.h

#ifndef _OGLDraw_h_
#define _OGLDraw_h_
#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);
};
#endif //_OGLDraw_h_

OGLDraw QGLWidget : initializeGL(), resizeGL() paintGL() ( 23.9).


draw(), y, .
.
23.10. OGLDraw.cpp. OGLDraw

OGLDraw::OGLDraw(QWidget* pwgt/*= 0*/) : QGLWidget(pwgt)


{
}

23.10 OGLDraw,
, - QGLWidget.
23.11. OGLDraw.cpp. initializeGL()

/*virtual*/void OGLDraw::initializeGL()
{
qglClearColor(Qt::white);
}

23.11 initializeGL()
.
23.12. OGLDraw.cpp. resizeGL()

/*virtual*/void OGLDraw::resizeGL(int nWidth, int nHeight)


{
glMatrixMode(GL_PROJECTION);

IV.

336
glLoadIdentity();
glViewport(0, 0, (GLint)nWidth, (GLint)nHeight);
glOrtho(0, 400, 200, 0, -1, 1);
}

23.12 resizeGL() 23.6.


23.13. OGLDraw.cpp. paintGL()

/*virtual*/void OGLDraw::paintGL()
{
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.13 paintGL(), draw() (. 23.14). x y, . . GL_POINTS ,


. GL_LINES
, , , . GL_LINE_STRIP
, , .
,
. GL_LINE_LOOP , . GL_TRIANGLE_STRIP .
, ,
. GL_POLYGON . GL_QUADS . GL_TRIANGLES
.
23.14. OGLDraw.cpp. draw()

void OGLDraw::draw(int xOffset, int yOffset, GLenum type)


{
int n = 8;
glPointSize(2);
glBegin(type);
glColor3f(0, 0, 0);
for (int i = 0; i < n; ++i) {
float fAngle = 2 * 3.14 * i / n;

23. OpenGL

337

int
x
= (int)(50 + cos(fAngle) * 40 + xOffset);
int
y
= (int)(50 + sin(fAngle) * 40 + yOffset);
glVertex2f(x, y);
}
glEnd();
}

23.14 draw(), type , .


glPointSize().
2. glColor*() .
glVertex*() .


. 23.4 , ,
X Y .

. 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();
}

( 23.15) OpenGL- OGLPyramid.


23.16. OGLPyramid.h

#ifndef _OGLPyramid_h_
#define _OGLPyramid_h_

IV.

338
#include <QGLWidget>

// ======================================================================
class OGLPyramid : public QGLWidget {
private:
GLuint m_nPyramid;
GLfloat m_xRotate;
GLfloat m_yRotate;
QPoint m_ptPosition;
protected:
virtual
virtual
virtual
virtual
virtual

void
void
void
void
void
GLuint

initializeGL
(
);
resizeGL
(int nWidth, int nHeight);
paintGL
(
);
mousePressEvent(QMouseEvent* pe
);
mouseMoveEvent (QMouseEvent* pe
);
createPyramid (GLfloat fSize = 1.0f
);

public:
OGLPyramid(QWidget* pwgt = 0);
};
#endif //_OGLPyramid_h_

OGLPyramid ( 23.16) m_nPyramid,


.

, , . ,
QPicture.
.

m_xRotate, m_yRotate X Y.
m_ptPosition .
, QGLWidget,
mousePressEvent() mouseMoveEvent() . createPyramid() .
23.17. OGLPyramid.cpp. OGLPyramid

OGLPyramid::OGLPyramid(QWidget* pwgt/*= 0*/) : QGLWidget(pwgt)


, m_xRotate(0)
, m_yRotate(0)
{
}

OGLPyramid -

QGLWidget ( 23.17).

23. OpenGL

339

23.18. OGLPyramid.cpp. initializeGL()

/*virtual*/void OGLPyramid::initializeGL()
{
qglClearColor(Qt::black);
glEnable(GL_DEPTH_TEST);
glShadeModel(GL_FLAT);
m_nPyramid = createPyramid(1.2f);
}

qglClearColor() ( 23.18). glEnable() . , , glShadeMode() GL_FLAT,


.
createPyramid() (. 23.23) , m_nPyramid. ,
, .
23.19. OGLPyramid.cpp. resizeGL()

/*virtual*/void OGLPyramid::resizeGL(int nWidth, int nHeight)


{
glViewport(0, 0, (GLint)nWidth, (GLint)nHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(-1.0, 1.0, -1.0, 1.0, 1.0, 10.0);
}

23.19 glViewPort()
. glMatrixMode() .
glLoadIdentity() . glFrustum() .
, , , , .
Z; .
23.20. OGLPyramid.cpp. paintGL()

/*virtual*/void OGLPyramid::paintGL()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
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);
}

IV.

340

, ( 23.20).
glLoadIdentity() .
y glTranslate() Z 3 . glRotate() X Y ,
m_xRotate m_yRotate. glCallList() .
23.21. OGLPyramid.cpp. mousePressEvent()

/*virtual*/void OGLPyramid::mousePressEvent(QMouseEvent* pe)


{
m_ptPosition = pe->pos();
}

m_ptPosition ( 23.21).
23.22. OGLPyramid.cpp. mouseMoveEvent()

/*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();
}

( 23.22) X Y. updateGL() ,
. m_ptPosition .
23.23. OGLPyramid.cpp. createPyramid()

GLuint OGLPyramid::createPyramid(GLfloat fSize/*=1.0f*/)


{
GLuint n = glGenLists(1);
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);

23. OpenGL

341

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;
}

createPyramid() ( 23.23). glGenLists() .


glNewList(). , GL_COMPILE, , . , glNewList() glEndList(), . GL_TRIANGLE_FAN , . . , ,
. GL_QUADS .

OpenGL API. , 17 . Qt OpenGL. Qt- OpenGL QGLWidget : initializeGL(), resizeGL()


paintGL().
OpenGL . OpenGL . ,
.
,
show() showFullScreen().

24


,
; , , .
. .

. , : ,
, . . Qt ,
.

QPrinter
QPrinter . , QPaintDevice, . QPainter,
.
QPrinter , ,
QPaintDevice. , , , . . Qt ,
. QPrintDialog
(. 33). :
setOrientation() ,
QPrinter::Portrait QPrinter::Landscape

;
setNumCopies() ;
setFromTo() ;
setColorMode() - . -

QPrinter::Color, -
QPrinter::Grayscale;
setPageSize() .

, . 24.1.

24.

343
24.1. PageSize QPrinter

()

()

()

A0

8411189

B0

10301456

B10

3245

A1

594841

B1

7281030

C5E

163229

A2

420594

B2

515728

Comm10E

105241

A3

297420

B3

364515

DLE

110220

A4

210297

B4

257364

Executive

191254

A5

148210

B5

182257

Folio

210330

A6

105148

B6

128182

Ledger

432279

A7

74105

B7

91128

Legal

216356

A8

5274

B8

6491

Letter

216279

A9

3752

B9

4564

Tabloid

279432

. setOutputFileName(). ,
,
. setDocName();
, , , .
, , PDF (Portable Document Format,
), , :
setOutputFormat() QPrinter::PdfFormat.
QPrinter setFontEmdeddingEnabled() -, ,
. ,
, .
, abort(), ,

.
, . 24.1,
. Print ()

.

. 24.1.

IV.

344
24.1. main.cpp

#include <QtGui>
#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.1, (
pprinter Printer, 24.224.6) (
pcmd). clicked() slotPrint() .
24.2. Printer.h

#ifndef _Printer_h_
#define _Printer_h_
#include <QWidget>
class QPrinter;
class QPaintDevice;
// ======================================================================
class Printer : public QWidget {
Q_OBJECT

24.

345

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();
};
#endif //_Printer_h_

Printer, 24.2,
QPrinter. draw() . ,
. slotPrint() .
24.3. Printer.cpp.

// ---------------------------------------------------------------------Printer::Printer(QWidget* pwgt/*=0*/) : QWidget(pwgt)


{
m_pprinter = new QPrinter;
}
// ---------------------------------------------------------------------/*virtual*/Printer::~Printer()
{
delete m_pprinter;
}

24.3, m_pprinter. , , ,
.
24.4. Printer.cpp. paintEvent()

/*virtual*/ void Printer::paintEvent(QPaintEvent* pe)


{
draw(this);
}

, 24.4,
draw() , , this.

IV.

346
24.5. Printer.cpp. slotPrint()

void Printer::slotPrint()
{
QPrintDialog dlg(m_pprinter, this);
dlg.setMinMax(1, 1);
if (dlg.exec() == QDialog::Accepted) {
draw(m_pprinter);
}
}

( dlg)
(m_pprinter) . , .
setMinMax() , . , 1 1.
exec() ,
. OK
QDialog::Accepted. QPrinter
m_pprinter draw().

,
,
QAbstractPrintDialog::toPage() QAbstractPrintDialog::fromPage(), . :
int nPages = dlg.toPage() dlg.fromPage() + 1;


,
QPrinter::newPage() m_pprinter draw().
24.6. 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.height());
painter.drawLine(r.width(), 0, 0, r.height());
painter.setBrush(Qt::NoBrush);
painter.setPen(QPen(Qt::red, 3, Qt::DashLine));
painter.drawEllipse(r);

24.

347

painter.setPen(Qt::blue);
painter.setFont(QFont("Times", 20, QFont::Normal));
painter.drawText(r, Qt::AlignCenter, "Printer Test");
}

draw(), 24.6, .
. , ,
, QPainter::viewport(). , drawRect(), drawLine(),
drawEllipse() drawText() , ,
. setPen() setBrush() , . setFont() .

, QPrinter QPaintDevice, , .
QPrinter , .
PDF.

25


;
.

. , , Qt
, . .


, , . QLineEdit ( 25.1),
(validator)
setValidator().
25.1. HexSpinBox

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() .;

25.

349

, , , ,

, private,
protected;
, ;
, ;
sizeHint() sizePolicy(), -

.

sizePolicy(), setSizePolicy()
.

. (. 6),
, . , , sizeHint() sizePolicy().
sizeHint() QSize, , . , , . 25.2 , .
sizeHint() .
pcmd1->sizeHint() (75, 23), pcmd2->sizeHint() (145, 23).
25.2. sizeHint()

QString str = "Button";


QPushButton* pcmd1 = new QPushButton(str);
QSize size = pcmd1->sizeHint(); // size = (75, 23)
str = "This is very long button label";
QPushButton* pcmd2 = new QPushButton(str);
size = pcmd2->sizeHint(); // size = (145, 23)

QWidget::sizePolicy() QSizePolicy, , ,
sizeHint() .
QSizePolicy ,
. 25.1.
25.1. SizeType QSizePolicy

Fixed

,
sizeHint(), ,

Minimum

,
sizeHint()

Maximum

,
sizeHint()

IV.

350

25.1 ()

Preferred

, sizeHint(), . . ,

MinimumExpanding

,
sizeHint().

Expanding

, sizeHint(), . , , ,

Ignored

, sizeHint(), .

, , QScrollView. . ,
, sizeHint(). , sizeHint(), .
QScrollView, .

setSizePolicy(), Expanding :
setSizePolicy(QSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);

25.3 , . 25.1. .
. , , .

. 25.1.

25.3. main.cpp

#include <QtGui>
#include "CustomWidget.h"
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QWidget
wgt;

25.

351

CustomWidget* pcw = new CustomWidget;


QScrollBar*
phsb = new QScrollBar(Qt::Horizontal);
phsb->setRange(0, 100);
QObject::connect(phsb, SIGNAL(valueChanged(int)),
pcw, SLOT(slotSetProgress(int))
);
//Layout setup
QVBoxLayout* pvbxLayout = new QVBoxLayout;
pvbxLayout->addWidget(pcw);
pvbxLayout->addWidget(phsb);
wgt.setLayout(pvbxLayout);
wgt.show();
return app.exec();
}

main() pcw, phsb ( 25.3).


valueChanged(int) slotSetProgress(int), ,
connect().
25.4. CustomWidget.h

#ifndef _CustomWidget_h_
#define _CustomWidget_h_
#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);

IV.

352
public slots:
void slotSetProgress(int n);
};
#endif //_CustomWidget_h_

25.4 CustomWidget
m_nProgress, . paintEvent() sizeHint().
. progressChanged(int),
.
slotSetProgress() .
25.5. CustomWidget.cpp. CustomWidget

CustomWidget::CustomWidget(QWidget* pwgt/*= 0*/) : QFrame(pwgt)


, m_nProgress(0)
{
setLineWidth(3);
setFrameStyle(Box | Sunken);
setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);
}

25.5 . setLineWidth() setFrameStyle()


. QSizePolicy::Minimum, setSizePolicy(), ,
, sizeHint().
QSizePolicy::Fixed , , sizeHint().
25.6. CustomWidget.cpp. paintEvent()

/*virtual*/ void CustomWidget::paintEvent(QPaintEvent*)


{
QPainter
painter(this);
QLinearGradient gradient(0, 0, width(), height());
float
f = m_nProgress / 100.0f;
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.

353

paintEvent() ( 25.6). painter . fillRect()


.
( f).
.
str , drawText() ( AlignCenter). &painter QFrame::drawFrame()
, QFrame .
25.7. CustomWidget.cpp. - slotSetProgress()

void CustomWidget::slotSetProgress(int n)
{
m_nProgress = n > 100 ? 100 : n < 0 ? 0 : n;
repaint();
emit progressChanged(m_nProgress);
}

25.7 slotSetProgress() ( m_nProgress) , 0 100. repaint() progressChanged(int)


.
25.8. CustomWidget.cpp. sizeHint()

/*virtual*/ QSize CustomWidget::sizeHint() const


{
return QSize(200, 30);
}

25.8 sizeHint() , .

QWidget , .
. , , .
, QWidget, .
QSizePolicy,
, /, . sizeHint() ,
,
QSizePolicy.

26


, .


Qt (look & feel). ,
Qt- , . , "
" - ,
, "" .
Qt ,
, , , . ,

. , , . , ,
. , ,
. , , " ", .
, , ,
,
, , . " , " , -
, , , ,
,
. , ,
, , . ? C ? ? , ?
.
. , , .
,
- ,

26.

355

, .
""
"" " : , , , ". , , . . ,
, .
Qt , , . , . .
. Qt , .
, , , .
, Qt.
, , , , ,
, . , .
CSS- Qt-.
Qt ,
QStyle , , . . Qt
, .
. 26.1 .
QStyle .

QStyle :
,
-reverse.

. 26.1.


.
. QStyle QCommonStyle, , . , QStyle.
QCommonStyle ,
Qt.

IV.

356


Qt- ,
. , , Windows
Motif. Qt (. 26.1):
QWindowsStyle, QMotifStyle, QPlastiqueStyle, QCDEStyle QClealookStyle . , QWindowsXPStyle QMacStyle,
"" . ,
Qt- -style, .
, setStyle() :
QApplication::setStyle(new QMotifStyle);

QApplication::setStyle(), . QObject,
,
QApplication. setStyle()
, delete .
setStyle(),
26.1, .
Qt , . .
. , , , , , (. 26.2).

. 26.2.

26.1. main.cpp

#include <QtGui>
// ---------------------------------------------------------------------QWidget* styledWidget(QStyle* pstyle)
{
QGroupBox*
pgr = new QGroupBox(pstyle->metaObject()->className());
QScrollBar*
psbr = new QScrollBar(Qt::Horizontal);
QCheckBox*
pchk = new QCheckBox("&Check Box");

26.

357

QSlider*
psld = new QSlider(Qt::Horizontal);
QRadioButton* prad = new QRadioButton("&Radio 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 = ::qFindChildren<QWidget*>(pgr);
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;
phbxLayout->addWidget(styledWidget(new QWindowsStyle));
phbxLayout->addWidget(styledWidget(new QMotifStyle));
phbxLayout->addWidget(styledWidget(new QCDEStyle));
phbxLayout->addWidget(styledWidget(new QCleanlooksStyle));
phbxLayout->addWidget(styledWidget(new QPlastiqueStyle));
wgt.setLayout(phbxLayout);
wgt.show();
return app.exec();
}

main() wgt ( 26.1). styledWidget() , .


( pgr), className() , , . .
QObject. (pgr)
(pvbxLayout) . ,
qFindChildren() pgr,
foreach setStyle(),
.

IV.

358

, . 26.3,
. .

. 26.3.

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();
}

26.2 MyApplication. 26.3, 26.4.


26.3. MyApplication.h

#ifndef _MyApplication_h_
#define _MyApplication_h_
#include <QWidget>
// ======================================================================
class MyApplication : public QWidget {
Q_OBJECT
public:
MyApplication(QWidget* pwgt = 0);
public slots:
void slotChangeStyle(const QString& str);
};
#endif

//_MyApplication_h_

26.

359

MyApplication ( 26.3) QWidget. ,


slotChangeStyle(const QString&),
.
26.4. MyApplication.cpp

#include <QtGui>
#include "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("&Radio Button");
QCheckBox*
pchk = new QCheckBox("&Check Box");
QPushButton* pcmd = new QPushButton("&Push Button");
pcbo->addItems(QStringList() <<
<<
<<
<<
<<
);

"Windows"
"Motif"
"CDE"
"Cleanlooks"
"Plastique"

connect(pcbo,
SIGNAL(activated(const QString&)),
SLOT(slotChangeStyle(const QString&))
);
//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);
}
// ---------------------------------------------------------------------void MyApplication::slotChangeStyle(const QString& str)
{
QStyle* pstyle = QStyleFactory::create(str);
QApplication::setStyle(pstyle);
}

360

IV.

26.4 MyApplication
, addItems() .
connect() activated(const QString&)
slotChangeStyle(const QString&). , .
QStyleFactory::create(), .
setStyle(), .


QStyle. QWidget::style(). QStyle : , , sizeHint() . .
Qt
. ,
, . QStyle,
. ,
, . , ,
.
QStyle , . , , , QStyle:
drawPrimitive() ;
drawControl() ;
drawComplexControl() .

, , . QStyleOption.
public, . . :
version () . QStyleOption -

, ;
type () ;
state () , :

(enabled), (active), (pressed) . .;


direction () ,
Qt::LeftToRight, Qt::RightToLeft;

rect (. ) , -

;
font () ;
palette () .

26.

361

,
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
const QStyleOption*
QPainter*
const QWidget*
)

elem,
popt,
ppainter,
pwgt = 0

, ,
. QStyleOption, . QPainter, . .
, , .


, , ,
.
drawControl():
void drawControl(ControlElement
const QStyleOption*
QPainter*
const QWidget*
)

elem,
popt,
ppainter,
pwgt = 0

IV.

362

, ,
. drawPrimitive().


, , , , . .
drawComplexControl():
void drawComplexControl(ComplexControl
const QStyleOptionComplex*
QPainter*
const QWidget*
)

control,
popt,
ppainter,
pwgt = 0

.
QStyleOption, ,
QStyleOptionComplex. QStyleOption
, , , . . , .


, , , , QComboBox.
, ,
, . ,
. 26.4, , .

. 26.4.

26.5. main.cpp

#include <QtGui>
#include "CustomStyle.h"
int main (int argc, char** argv)
{
QApplication app(argc, argv);
QWidget
wgt;

26.

363

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


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();
}

main(), 26.5, , QPushButton. setStyle()


CustomStyle.
26.6. CustomStyle.h

#ifndef _CustomStyle_h_
#define _CustomStyle_h_
#include <QWindowsStyle>
class QPainter;
// ======================================================================
class CustomStyle : public QWindowsStyle {
public:
virtual void polish (QWidget* pwgt);
virtual void unpolish(QWidget* pwgt);
virtual void drawPrimitive(
PrimitiveElement elem,
const QStyleOption*
popt,
QPainter*
ppainter,
const QWidget*
pwgt = 0
) const;
};
#endif

//_CustomStyle_h_

26.6 CustomStyle QWindowsStyle.


polish() unpolish(), QStyle.
.
,
.

364

IV.

drawPrimitive(), (primitive control element).


elem , .
QStyleOption.
QPainter ( ppainter), . pwgt , .
26.7. CustomStyle.cpp. polish()

void CustomStyle::polish(QWidget* pwgt)


{
if (qobject_cast<QPushButton*>(pwgt)) {
pwgt->setAttribute(Qt::WA_Hover, true);
}
}

polish() ( 26.7).
, Qt::WA_Hover
QPushButton true. ,
Qt .
.
26.8. CustomStyle.cpp. unpolish()

void CustomStyle::unpolish(QWidget* pwgt)


{
if (qobject_cast<QPushButton*>(pwgt)) {
pwgt->setAttribute(Qt::WA_Hover, false);
}
}

unpolish() ,
polish() ( 26.8). Qt::WA_Hover false.
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);

26.

365

if (pOptionButton) {
bool bDown = (pOptionButton->state & State_Sunken)
|| (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:
QWindowsStyle::drawPrimitive(elem, popt, ppainter, pwgt);
break;
}
return;
}

switch. case,
, . .
QStyleOption , ,
. , ,
QStyleOptionButton. ,
.
bDown
(btnprs.bmp) (btn.bmp).
QPainter::drawPixmap().
bHover true, .
QPainter::fillRect() , .
pwgt, , ,
. , , . .
QStyleOption. pwgt, , , , , .
, , . . default
.

IV.

366

QStyle

QStyle ,
. , , ,
, ,
, Qt.
, (QLabel), , . ,
26.10. . 26.5.

. 26.5. ,

26.10. CustomStyle.cpp

void MyLabel::paintEvent(QPaintEvent*)
{
QStylePainter
painter(this);
QStyleOptionButton option;
option.initFrom(this);
option.text = "This is a label";
painter.drawControl(QStyle::CE_PushButton, option);
}

QStylePainter. ""
, QPainter.
QStyleOptionPushButton, .
initFrom() , : , , ,
. . .
"This is a label".
drawControl() QStylePainter, .


, . , , C++. ,
C++ , , C++ , . ,

26.

367

, C++, , .
,
. Qt . CSS
(Cascading Style Sheets, ), HTML. Qt
, . . Qt Designer
(. 45) CSS-, .
, , . , qss.
, QApplication::setStyleSheet(), QWidget::setStyleSheet(). , -stylesheet
CSS-. , . .
Qt-. :
MyApp stylesheet MyStyle.qss


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);
}

368

IV.

, . ,
:
QPushButton, QLineEdit, QLabel {color: red}

, . ,
. :
.PushButton {color: red}


(*).
, , , QLabel#MyLabel QLabel "MyLabel".
,
, :
namespace MyNameSpace {
class MyClass : public QWidget {
...
};
}

CSS :
MyNameSpaceMyClass {
background-colode: black;
color: white;
}

, : COLOR = color = CoLoR . . .


CSS , /C++, /* */, :
/* */


, .
.
. , QComboBox :
QComboBox::drop-down {image: url(pic.png)}

, , :
QPushButton::menu-indicator {image: url(downarrow.png)}

. 26.1 .

26.

369
26.1.

::down-arrow

. , ,

::down-button

::drop-down

::indicator

::item

::menu-indicator

::title

::up-arrow

::up-button

, . :
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

IV.

370

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.11. simple.qss

/* Simple Style */
QPushButton {
min-width: 80px;
}
QPushButton {
border-image: url(:/style/btn.bmp) 5px;
border-width: 5px;
}
QPushButton:hover {
border-image: url(:/style/btnhvd.bmp) 5px;
border-width: 5px;
}

26.

371

QPushButton:pressed {
border-image: url(:/style/btnprs.bmp) 5px;
border-width: 5px;
}

26.11. , 80 .
, , . border-image border-width 5 , , .
26.12. main.cpp

#include <QtGui>
int main (int argc, char** argv)
{
QApplication app(argc, argv);
QWidget
wgt;
QPushButton* pcmdA = new QPushButton ("Button1");
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);
QFile file(":/style/simple.qss");
file.open(QFile::ReadOnly);
QString strCSS = QLatin1String(file.readAll());
qApp->setStyleSheet(strCSS);
wgt.show();
return app.exec();
}

26.12, 26.5, , . ,
,
strCSS QApplicaiton::setStyleSheet() .
, , , :
qApp->setStyleSheet("QPushButton::hover {background-color: blue}");

IV.

372

, , , ( 26.6).
26.13.

QPushButton {
min-width: 16px;
background: qlineargradient(x1:0, y1:1, x2:0, y2:0,
stop:1 rgb(133,133,135),
stop:0.4 rgb(31, 31, 33) );
color: white;
border: 1px solid white;
border-radius:5px;
}

. 26.6.

, 16 ( minwidth). , background, .
(x1, y1) (x2, y2) , 1 0.4.
, - -
. , ( color).
, ( border) ( border-radius).
26.14.

QPushButton:hover {
background: qlineargradient(x1:0, y1:1, x2:0, y2:0,
stop:1 rgb(133,133,135),
stop:0.4 rgb(31, 31, 33),
stop:0.2 rgb(0, 0, 150) );
}

26.14 , ,
. ,
26.13, . .

26.

373

26.15.

QPushButton:pressed {
background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
stop:0 rgba(1, 1, 5, 80),
stop:0.6 rgba(18, 18, 212, 80),
stop:0.5 rgba(142, 142, 245,80) );
border: 1px solid rgb(18, 18, 212);
}

( 26.15)
. ,
.
26.16.

QPushButton:checked {
background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
stop:1 rgb(133,133,135),
stop:0.4 rgb(31, 31, 33) );
border: 1px solid rgb(18, 18, 212);
}

(toggle),
, , ,
- ( 26.16).
26.17.

QPushButton:checked:hover {
background: qlineargradient(x1:0, y1:1, x2:0, y2:0,
stop:1 rgb(31, 31, 33),
stop:0.4 rgb(133,133,135),
stop:0.1 rgb(0, 0, 150) );
}


,
( 26.17).
,
border-radius. ,
. ,
.
border-image. , ,
,
. borderimage 9 , . 26.7.

IV.

374

,
.
border-image :
1. top ;
2. right ;
3. bottom ;
4. left .
. 26.7
:
border-image: url(button.png) 9, 2, 5, 2

, , top, right,
bottom left . :
border-image: url(button.png) 5

. 26.7. ,

Qt
(look & feel) .
, . ,
,
QApplication::setStyle().
.
, .
. , .
, .
QStyleOption.
Qt , CSS. CSS- C++ ,
, . .
, , .

27

? ? ?
""

, 30% .
.
, .
, ,
.


, . ,
QApplication::beep(). , , .
, ,
, .
, , - .

,
, , , , ,
28, Phonon.

Qt QSound.
play(),
. ,
, . :
QSound::play("music/yesterday.wav");

,
, QSound. setLoops(), -

376

IV.

. 1 .
play():
QSound sound("music/yesterday.wav");
sound.setLoops(3); // 3
sound.play();

,
QSound::loopsRemaining(), .
, QSound::stop().

:
sound.stop();

, , , QSound
play().
, , QSound::isFinished(), true
, , false, . , isFinished()
false.


WAV.
Windows.
:
;
;
c 16- 8- ;
11 48 .

WAV QSound. , .
,
.
QSound QSound::isAvailable().
QSound::isAvailible() . true, , false.

,
, ,
(. 27.1). Play () , Stop () .
Loop () (toggle button) (. 8), . . -

27.

377

(on) (off). ,
:
,
, Stop ().

. 27.1. ,

27.1. SoundPlayer.pro

x11:REQUIRES
TEMPLATE
HEADERS
SOURCES
TARGET

=
=
=
=
=

nas
app
SoundPlayer.h
SoundPlayer.cpp main.cpp
../SoundPlayer

27.1 x11:REQUIRES
Windows, , X11, . .
NAS (Network Audio System, ),
http://radscan.com/nas.html.
27.2. main.cpp

#include <QApplication>
#include "SoundPlayer.h"
int main(int argc, char** argv)
{
QApplication app(argc, argv);
SoundPlayer soundPlayer;
soundPlayer.show();
return app.exec();
}

27.2 SoundPlayer.
27.3. SoundPlayer.h

#ifndef _SoundPlayer_h_
#define _SoundPlayer_h_
#include <QWidget>

IV.

378
class QSound;

// ======================================================================
class SoundPlayer : public QWidget {
Q_OBJECT
private:
QSound* m_psnd;
public:
SoundPlayer(QWidget* pwgt = 0);
public slots:
void slotPlay
(
);
void slotStop
(
);
void slotLoopToggled(bool);
};
#endif //_SoundPlayer_h_

27.3 SoundPlayer. (m_psnd)


QSound, : slotPlay(), slotStop() slotLoopToggled().
,
.
27.4. SoundPlayer.cpp

#include <QtGui>
#include "SoundPlayer.h"
// ---------------------------------------------------------------------SoundPlayer::SoundPlayer(QWidget* pwgt/*=0*/) : QWidget(pwgt)
{
if (!QSound::isAvailable()) {
QMessageBox::warning(this,
"No Sound",
"Sorry, I can't play the sound"
);
}
QPushButton* pcmdPlay = new QPushButton("&Play");
QPushButton* pcmdStop = new QPushButton("&Stop");
QPushButton* pcmdLoop = new QPushButton("&Loop");
pcmdLoop->setCheckable(true);
pcmdLoop->setChecked(true);
connect(pcmdPlay, SIGNAL(clicked()), SLOT(slotPlay()));
connect(pcmdStop, SIGNAL(clicked()), SLOT(slotStop()));
connect(pcmdLoop, SIGNAL(toggled(bool)),SLOT(slotLoopToggled(bool)));
m_psnd = new QSound("music/yesterday.wav", this);

27.

379

//Layout setup
QHBoxLayout* phbxLayout = new QHBoxLayout;
phbxLayout->addWidget(pcmdPlay);
phbxLayout->addWidget(pcmdStop);
phbxLayout->addWidget(pcmdLoop);
setLayout(phbxLayout);
slotLoopToggled(true);
}
// ---------------------------------------------------------------------void SoundPlayer::slotPlay()
{
m_psnd->play();
}
// ---------------------------------------------------------------------void SoundPlayer::slotStop()
{
m_psnd->stop();
}
// ---------------------------------------------------------------------void SoundPlayer::slotLoopToggled(bool b)
{
m_psnd->setLoops(b ? -1 : 1);
m_psnd->stop();
}

SoundPlayer ( 27.4) isAvailable() . : ( pcmdPlay), ( pcmdStop)


( pcmdLoop).
, setCheckable()
true. setChecked() . C slotLoopToggled(bool) toggled(bool)
Loop (). toggled(bool) . , ,
. slotLoopToggled(bool):
setLoop() stop() . ,
.

, Qt
. , , , .

28

, .

-, ,
, , Web-, c .
, , , .
, ,
. ,
.
. .
? "
", , . . 50- .

, -
. "" : "multum" "", "medium" " ". , , . ,
, , , , , Web . . , , . Phonon,
Qt.

Phonon
KDEMM (KDE MultiMedia). API KDE4 ( . Kool Desktop Environment) UNIX- .
, , . . KDE. , Phonon.

28.

381

Phonon , . Phonon,
. , , ,
Phonon. , Phonon , ,
(18951971 .).
, Phonon , KDE- ( 4) Qt- Windows Mac OS X , , , Linux. Linux ,
, , , GStreamer, Xine . . Phonon . API,
. (backend).
.
Phonon .
, Phonon QtCore, QGui, .
Phonon : Phonon, ,
, . , ,
,
, .

Windows Phonon DirectX DirectShow 9
. , Microsoft
DirectX 9 SDK. , ,
Qt4 "Phonon Overview". Visual C++ 2008,
, . . .

, Phonon ,
. , , , Phonon .
.

Phonon
, - ,
, Phonon, .
Phonon, Phonon::.
Phonon, using namespace Phonon
. . 28.1 , Phonon,
.
Phonon : , . MediaObject. , ,

IV.

382

Phonon, c , CD
DVD, . ,
, , - ,
, , , start(), stop(), pause().

. 28.1. Phonon

MediaSource.
QMetaObject setCurrentSource().
. . , , . .
, . :
QString strArtist = media->metaData("ARTIST"));


QString strArtist = media->metaData(Phonon::ArtistMetaData));

. 28.1 , .
28.1. Phonon::MetaData

ArtistMetaData

AlbumMetaData

TitleMetaData

DataMetaData

GenreMetaData

TracknumberMetaData

28.

383
28.1 ()

DescriptionMetaData

MusicBrainzDiscIdMetaData

metaDataChanged() , .
AudioOutput .
VideoWidget, QWidget,
.
, MediaObject, AudioOuput, Effect, VideoWidget
MediaNode, .
Path. createPath().
,
. . 28.2.

. 28.2. Phonon

IV.

384

Effect.
: EffectParameter EffectWidget. - , .
ObjectDescription Phonon . description(),
, name(), .
, , ,
QSlider. , , , QSlider
, . .
. : SeekSlider
VolumeSlider, . ,
,
QSlider.
MediaController . , DVD (chapters),
.
, , , ,
VideoPlayer . , MediaObject, VideoWidget, AudioOutput,
Path. , mediaObject(), audioOutput() videoWidget().
VideoPlayer , , : Play, Pause,
Stop . . ,
VideoPlayer, MediaObject AudioOutput, 28.1.


, Phonon, . , Phonon
. 28.1 .
.

, ( pro) QT += phonon.
28.1. . main.cpp

#include <QApplication>
#include <phonon>
int main(int argc, char** argv)

28.

385

{
QApplication
app(argc, argv);
Phonon::MediaObject media;
Phonon::AudioOutput ao(Phonon::MusicCategory);
Phonon::createPath(&media, &ao);
QObject::connect(&media, SIGNAL(finished()), &app, SLOT(quit()));
media.setCurrentSource(Phonon::MediaSource("music/yesterday.wav"));
media.play();
return app.exec();
}

MediaObject AudioOutput.
28.1 media ao,
AudioOuput MusicCategory, , . AudioOutput
, .
, MediaObject, , . .
.
createPath() media ao.
, ,
. finished() quit().
setCurrentSource() . ,
QUrl, ,
, QIODevice.

CD, DVD VCD MediaSource
Phonon::Cd, Phonon::Dvd Phonon::Vcd ,
. , , .


, , ,
, . enqueue(). , 28.1
setCurrentSource() media.enqueue("test.mp3"),
.

, play(). ,
, .

IV.

386


( 28.1) AudioOuput
. .
, VideoWidget. , Windows DirectShow,
Mac OS X QuickTime, Linux GStreamer.
, . 28.3.

. 28.3.

28.2. . main.cpp

#include <QApplication>
#include "MediaPlayer.h"
int main(int argc, char** argv)
{
QApplication app(argc, argv);
MediaPlayer mediaPlayer;
mediaPlayer.show();
return app.exec();
}

( 28.2)
(mediaPlayer).
28.3. MediaPlayer.h

#ifndef _MediaPlayer_h_
#define _MediaPlayer_h_

28.

387

#include <QWidget>
namespace Phonon {
class AudioOutput;
class MediaObject;
}
// ======================================================================
class MediaPlayer : public QWidget {
Q_OBJECT
private:
Phonon::AudioOutput* m_pao;
Phonon::MediaObject* m_pmedia;
public:
MediaPlayer(QWidget* pwgt = 0);
public slots:
void slotLoad();
};
#endif //_MediaPlayer_h_

MediaPlayer ( 28.3)
AudioOutput ( m_pao) MediaObject ( m_pmedia), (forward declaration) , , Phonon. slotLoad().
28.4. MediaPlayer.cpp. MediaPlayer

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


{
m_pmedia = new Phonon::MediaObject(this);
m_pao
= new Phonon::AudioOutput(Phonon::VideoCategory, this);
Phonon::VideoWidget* pvw = new Phonon::VideoWidget;
Phonon::createPath(m_pmedia, m_pao);
Phonon::createPath(m_pmedia, pvw);
QPushButton*
QPushButton*
QPushButton*
QPushButton*
Phonon::VolumeSlider*
Phonon::SeekSlider*

pcmdPlay
pcmdStop
pcmdPause
pcmdLoad
psldVolume
psldSeek

=
=
=
=
=
=

new
new
new
new
new
new

QPushButton("&Play");
QPushButton("&Stop");
QPushButton("P&ause");
QPushButton("&Load");
Phonon::VolumeSlider;
Phonon::SeekSlider;

psldSeek->setMediaObject(m_pmedia);
psldVolume->setAudioOutput(m_pao);
psldVolume->setOrientation(Qt::Vertical);
psldVolume->setMaximumHeight(30);

IV.

388

connect(pcmdPlay, SIGNAL(clicked()), m_pmedia, SLOT(play()));


connect(pcmdStop, SIGNAL(clicked()), m_pmedia, SLOT(stop()));
connect(pcmdPause, SIGNAL(clicked()), m_pmedia, SLOT(pause()));
connect(pcmdLoad, SIGNAL(clicked()), SLOT(slotLoad()));
//Layout setup
QHBoxLayout* phbxLayout = new QHBoxLayout;
phbxLayout->addWidget(pcmdPlay);
phbxLayout->addWidget(pcmdPause);
phbxLayout->addWidget(pcmdStop);
phbxLayout->addWidget(psldSeek);
phbxLayout->addWidget(pcmdLoad);
phbxLayout->addWidget(psldVolume);
QVBoxLayout* pvbxLayout = new QVBoxLayout;
pvbxLayout->addWidget(pvw);
pvbxLayout->addLayout(phbxLayout);
setLayout(pvbxLayout);
}

( 28.4) MediaObject (
m_pmedia), AudioOutput ( m_pao) VideoWidget (pvw). AudioOutput
VideoCategory, , . , Play, Stop, Pause Load . VolumeSlider SeekSlider, Phonon.
, ,
, setMediaObject() ( m_pmedia).
, setAudioOutput() ( m_pao).
setOrientation() Vertical. clicked() Play, Stop Pause
. Load c slotLoad().
28.5. MediaPlayer.cpp. slotLoad()

void MediaPlayer::slotLoad()
{
QString str = QFileDialog::getOpenFileName(0, "Load", "", "*.*");
if (!str.isEmpty()) {
m_pmedia->setCurrentSource(Phonon::MediaSource(str));
}
}

slotLoad(), 28.5,
. ,
setCurrentSource().

28.

389

VideoWidget, . VideoWidget . , setBrightness() setContrast().


1 1, 0.
VideoWidget ,
, . , setScaleMode() VideoWidget::ScaleAndCrop.
. VideoWidget enterFullScreen(),
exitFullScreen(). , setFullScreen()
: true false
. ,
, isFullScreen().

Phonon ,
. API
( ) . , ,
QUrl.
Phonon :
, ,

;
;
;
, .

MediaObject .
AudioOutput , VideoWidget
. , Path.
,
Path.
. , .
VideoPlayer,
.

390

IV.


, .
.

29.

30.

31.

32.

33.

34.

35.

SDI- MDI-

36.

(Desktop)

29


...
,
.
, - 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");

setValue().
, . ,

394

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
. . value() . , , , . :
QString str = settings.value("/Settings/StringKey", "").toString();
int
n
= settings.value("/Settings/IntegerKey", 0).toInt();
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.endGroup();
settings.endGroup();

, 29.129.8, , . 29.1.
.
Classic
(), , , Borland (
""), , . Disable edit ( ) / .
.
29.1. main.cpp

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

29.
int main(int argc, char** argv)
{
QApplication app(argc, argv);
MyProgram
myProgram;
myProgram.show();
return app.exec();
}

. 29.1. ,

29.1 MyProgram.
29.2. MyProgram.h

#ifndef _MyProgram_h_
#define _MyProgram_h_
#include <QWidget>
#include <QSettings>
class
class
class
class

QComboBox;
QCheckBox;
QTextEdit;
QLabel;

// ======================================================================
class MyProgram : public QWidget {
Q_OBJECT
private:
QSettings m_settings;
QComboBox* m_pcbo;
QCheckBox* m_pchk;

395

V.

396
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);
};
#endif //_MyProgram_h_

MyProgram, 29.2, m_settings


QSettings. ( m_pcbo),
(m_pchk), (m_ptxt), (m_plbl) (m_nCounter). MyProgram
(writeSettings() readSettings()). , slotCheckedBoxClicked() slotComboBoxActivated(),
, .
29.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))
);
readSettings();
//Layout setup
QVBoxLayout* pvbxLayout = new QVBoxLayout;
QHBoxLayout* phbxLayout = new QHBoxLayout;

29.

397

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);
}

29.3 m_settings :
"BHV" "MyProgram". (m_plbl), (m_ptxt), (m_pcbo) (m_pchk). addItem()
Classic Borland, .
clicked() ( m_pchk)
slotCheckBoxClicked(), activated(int)
slotComboBoxActivated(int). readSettings(). (. 6).
29.4. MyProgram.cpp. readSettings()

void MyProgram::readSettings()
{
m_settings.beginGroup("/Settings");
QString
int
int
int
bool

strText
nWidth
nHeight
nComboItem
bEdit

=
=
=
=
=

m_settings.value("/text", "").toString();
m_settings.value("/width", width()).toInt();
m_settings.value("/height", height()).toInt();
m_settings.value("/highlight", 0).toInt();
m_settings.value("/edit", true).toBool();

m_nCounter = m_settings.value("/counter", 1).toInt();


QString str = QString().setNum(m_nCounter++);
m_plbl->setText("This program has been started " + str + " times");
m_ptxt->setPlainText(strText);
resize(nWidth, nHeight);
m_pchk->setChecked(bEdit);
slotCheckBoxClicked();
m_pcbo->setCurrentIndex(nComboItem);
slotComboBoxActivated(nComboItem);
m_settings.endGroup();
}

V.

398

29.4 readSettings(),
beginGroup() QSettings .
, . strText /text, readEntry().
/text , ,
, . . . nWidth nHeight, , nComboItem,
, bEdit, , m_nCounter, . .
m_nCounter . ,
, endGroup().
29.5. MyProgram.cpp. ~MyProgram()

/*virtual*/MyProgram::~MyProgram()
{
writeSettings();
}

, 29.5, , , . . . writeSettings().

closeEvent(),
.

29.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();
}

writeSettings()
beginGroup() .
setValue(), , ( 29.6).

29.

399

29.7. MyProgram.cpp. slotCheckBoxClicked()

void MyProgram::slotCheckBoxClicked()
{
m_ptxt->setEnabled(!m_pchk->isChecked());
}

slotCheckBoxClicked() ,
isChecked() ( 29.7).
29.8. MyProgram.cpp. slotComboBoxActivated()

void MyProgram::slotComboBoxActivated(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);
}

slotComboBoxActivated(), 29.8,
n.
QPalette::Active (. 13).
. QApplication . ( 29.9).
29.9.

class App : public QApplication {


Q_OBJECT
private:
QSettings* m_pSettings;
public:
App(int& argc,
char** argv,
const QString& strOrg,
const QString& strAppName
) : QApplication(argc, argv)
, m_pSettings(0)

V.

400
{
setOrganizationName(strOrg);
setApplicationName(strAppName);

m_pSettings = new QSettings(strOrg, strAppName, this);


}
static App* theApp()
{
return (App*)qApp;
}
QSettings* settings()
{
return m_pSettings;
}
};

argc, argv
QApplication. strOrg
strAppName. QCoreApplication::setOrganizationName() QCoreApplication::
setApplicationName()
( m_pSettings). theApp() ,
.
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");


,
, .
.
, . ,
.

29.

401

QApplication QApplication::commitData() QApplication::saveState(),


. QSessionManager. , ,
allowInteraction(), ,
. cancel()
, . setRestartHint() ,
.
:
RestartIfRunning , -

, ;
RestartAnyway

;
RestartImmediately -

;
RestartNever .

QApplication::isSessionRestored() ,
, ( true) (false).
, . 29.2,
.

. 29.2. ,

29.10. main.cpp

#include <QtGui>
// ======================================================================
class MyApplication : public QApplication {
public:
// -----------------------------------------------------------------MyApplication(int argc, char** argv)
: QApplication(argc, argv)
{
}
// -----------------------------------------------------------------virtual ~MyApplication()
{
}

V.

402

// -----------------------------------------------------------------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();
}

29.10 MyApplication QApplication.


commitData(), . . QApplication
MyApplication.

Qt , , . .
, , /.
, QVariant. value()
setValue().

.
.

30


?
, ?
.


.
: . ,
, .


(Clipboard) . . ,
. . , , : (cut), (opy) (paste),
"" , : <Ctrl>+<X>, <Ctrl>+<C> <Ctrl>+<V> .
Qt QClipboard. , . . . QClipboard
dataChanged() ,
. ,
, . :
connect(qApp->clipboard(), SIGNAL(dataChanged()),
pwgt, SLOT(slotDataControl())
);

setText(), setPixmap(),
setImage() setMimeData(). :
QClipboard* pcb = QApplication::clipboard();
pcb->setText("My Text");

V.

404


setMimeData() .
, QMimeSource.
QMimeSource , ,
.

text(), image(), pixmap() mimeData()


. :
QClipboard* pcb = QApplication::clipboard();
QString
str = pcb->text();
if (!str.isNull()) {
qDebug() << "Clipboard Text: " << str;
}

(drag & drop) . , ,


.
.
: ,
, , , . ,
. Recycle Bin
() Windows,
.
QWidget , .
, ,
, . , QTextEdit (. 10) .
Qt QDrag,
QMimeData. "MIME"
Multipurpose Internet Mail Extension ( ). , ,
- . , MIME-
text/plain , ASCII-, text/html , HTML .
image/*. , jpg
MIME- image/jpg. ,
,
application/*. . 30.1 .
, MIME Qt QMimeData.
:
setColorData();
setImageData();
setText();

30.

405

HTML setHtml();
() URL (Uniform Resource Locator, -

) setUrls(). .
30.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). , . . 30.1
.

. 30.1.

V.

406

drag
mousePressEvent()
mouseMoveEvent(). , . mouseMoveEvent() .
. 30.2.

. 30.2.

30.1. Drag.h

#ifndef _Drag_h_
#define _Drag_h_
#include <QtGui>
#include "img1.xpm"
// ======================================================================
class Drag : public QLabel {
Q_OBJECT
private:
QPoint m_ptDragPos;
void startDrag()
{
QMimeData* pMimeData = new QMimeData;
pMimeData->setText(text());
QDrag* pDrag = new QDrag(this);
pDrag->setMimeData(pMimeData);
pDrag->setPixmap(QPixmap(img1_xpm));
pDrag->exec();
}

30.

407

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);
}
public:
Drag(QWidget* pwgt = 0) : QLabel("This is draggable text", pwgt)
{
}
};
#endif //_Drag_h_

Drag, 30.1, m_ptDragPos,


. mousePressEvent()
, .
mouseMoveEvent() . ,
, . .
, . ,
,
. ,
startDragDistance() ( 4 ), , .
startDrag(). QMimeData,
, setText(), .
QDrag, , .
!
,
. -

V.

408

. , .

setPixmap() ,
. exec() . , , . , Qt::CopyAction,
Qt::MoveAction, Qt::LinkAction. Qt::MoveAction.

drop
. 30.3 , (
). .

. 30.3. ,

30.2. Drop.h

#ifndef _Drop_h_
#define _Drop_h_
#include <QtGui>
// ======================================================================
class Drop : public QLabel {
Q_OBJECT
protected:
virtual void dragEnterEvent(QDragEnterEvent* pe)

30.

409

{
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.toString() + "\n";
}
setText("Dropped:\n" + str);
}
public:
Drop(QWidget* pwgt = 0) : QLabel("Drop Area", pwgt)
{
setAcceptDrops(true);
}
};
#endif //_Drop_h_

,
Drop setAcceptDrops(),
true ( 30.2). , dragEnterEvent() dropEvent().
dragEnterEvent() , (. . 30.1).
, (, ,
<Ctrl>),
.
,
hasFormat().

MIME- , .
"text/uri-list".

acceptProposedAction() QDragEnterEvent .

QDragEnterEvent QDragMoveEvent (. . 14.1).
accept() ignore(), ( ) . -

V.

410

QRect. . , , , : accept(rect()).

dropEvent() , . urls()
QMimeData urlList.
foreach QUrl::toString() ,
("\n") .
setText().


Qt , ,
, .
.
, ,
. mimeType, , . , , 30.3.
30.3.

MyDragClass::startDrag()
{
QImage
img("mira.jpg");
QByteArray data;
QBuffer
buf(&data);
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);
}

30.3 , . ,
QMimeData::setImageData(), , . ,
QMimeData, QByteArray
QBuffer. QImage::save()
QBuffer, (data). QMimeData::setData().
image/jpg .

30.

411

,
:
QByteArray . .
,
, MIME-. , . ,
,
. ,
. 30.4, , , , .

. 30.4. ,

30.4. main.cpp

#include <QApplication>
#include "Widget.h"
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
Widget
wgt1;
Widget
wgt2;
wgt1.setWindowTitle("Widget1");
wgt1.setObjectName("Widget1");
wgt1.resize(200, 200);
wgt1.show();
wgt2.setWindowTitle("Widget2");
wgt2.setObjectName("Widget2");
wgt2.resize(200, 200);
wgt2.show();
return app.exec();
}

V.

412

( 30.4) Widget,
30.730.13.
,
setWindowTitle().
"Widget1" "Widget2" setObjectName().
30.5. WidgetDrag.h. WidgetMimeData

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;
}
};

MIME- ( 30.5)
, WidgetMimeData m_pwgt. mimeType() MIME-, "application/widget".
"application" , . "widget" ,
. setWidget().
m_pwgt , setData(),
MIME- QByteArray. widget().

30.

413

30.6. WidgetDrag.h. WidgetDrag

class WidgetDrag : public QDrag {


public:
WidgetDrag(QWidget* pwgtDragSource = 0) : QDrag(pwgtDragSource)
{
}
void setWidget(QWidget* pwgt)
{
WidgetMimeData* pmd = new WidgetMimeData;
pmd->setWidget(pwgt);
setMimeData(pmd);
}
};

WidgetDrag ( 30.6) ,
QDrag. setWidget(),
MIME- WidgetMimeData. setWidget() (pwgt). setMimeData() MIME- ( pmd) .
30.7. Widget.h

#ifndef _Widget_h_
#define _Widget_h_
#include <QPoint>
#include <QLabel>
// ======================================================================
class Widget : public QLabel {
Q_OBJECT
private:
QPoint m_ptDragPos;
void startDrag();
protected:
virtual
virtual
virtual
virtual

void
void
void
void

mousePressEvent(QMouseEvent*
);
mouseMoveEvent (QMouseEvent*
);
dragEnterEvent (QDragEnterEvent*);
dropEvent
(QDropEvent*
);

public:
Widget(QWidget* pwgt = 0);
};
#endif //_Widget_h_

414

V.

, MIME- ( 30.7). , QLabel.


, .
,
.
30.8. Widget.cpp.

Widget::Widget(QWidget* pwgt/*=0*/) : QLabel(pwgt)


{
setAcceptDrops(true);
}

, 30.8,
, true setAcceptDrops().
30.9. Widget.cpp. startDrag()

void Widget::startDrag()
{
WidgetDrag* pDrag = new WidgetDrag(this);
pDrag->setWidget(this);
pDrag->exec(Qt::CopyAction);
}

startDrag()
this ( 30.9). , , this setWidget(). exec().
30.10. Widget.cpp. mousePressEvent()

/*virtual*/ void Widget::mousePressEvent(QMouseEvent* pe)


{
if (pe->button() == Qt::LeftButton) {
m_ptDragPos = pe->pos();
}
QWidget::mousePressEvent(pe);
}

mousePressEvent()
m_ptDragPos ( 30.10).
30.11. Widget.cpp. mouseMoveEvent()

/*virtual*/ void Widget::mouseMoveEvent(QMouseEvent* pe)


{
if (pe->buttons() & Qt::LeftButton) {
int distance = (pe->pos() m_ptDragPos).manhattanLength();

30.

415

if (distance > QApplication::startDragDistance()) {


startDrag();
}
}
QWidget::mouseMoveEvent(pe);
}

mouseMoveEvent() ( 30.11) .
, 30.1,
.
30.12. Widget.cpp. dragEnterEvent()

/*virtual*/ void Widget::dragEnterEvent(QDragEnterEvent* pe)


{
if (pe->mimeData()->hasFormat(WidgetMimeData::mimeType())) {
pe->acceptProposedAction();
}
}

dragEnterEvent() ( 30.12)
, "application/widget", hasFormat().
WidgetMimeData::mimeType().
30.13. Widget.cpp. dropEvent()

/*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()));
}
}

mimeData() ( 30.13). , , WidgetMimeData.


, widget().
setText().

.
, .

416

V.

. (drag & drop) .


Drag & drop .
( ).
, .
, . , Windows . ,
, ,
.
Qt QDrag drag & drop
QMimeData .
,
mousePressEvent() mouseMoveEvent(). dragEnterEvent() dropEvent(), (
) setAcceptDrops(), true.
Qt .

31


.
.
. "!!!" .
"-8" .

,
. .
. , . .
, . ,
, 100
, 98% . , , , ,
, , "",
2% . , !
Qt- :
1. ( ).
2. lupdate.
3. (
Qt Linguist).
4. lrelease , QTranslator.
.


.
, , ,
tr(), QObject.
, , . .
tr() . ,

V.

418

,
. :
setText(tr("Yes"));

tr() QString::arg():
setText(tr("User Name: %1").arg(strName));

tr() , , , ,
. , "" ,
. , . :
QLabel lbl(tr("Location", "On the map"));

tr() ,
, , ""
, . :
QKeySequence keyseq(tr("CTRL+L"));

. -:
tr() , .
:
int n = getDays();
QLabel lbl(tr("day(s):", "Plural or singular", n));

, , ,
, .

i18n, ,
"internationalization". , 18,
. "localization" l10n
().

, , .
, 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

, , , . , .
:
qApp->setLayoutDirection(Qt::RightToLeft);

31.

419

lupdate
tr() . lupdate.
tr() , . , tr(), TS- (Translation Source, ) . , 31.1 . 31.1,
,
:
lupdate main.cpp -ts main_ru.ts main_de.ts


lupdate , .

. 31.1.

31.1. main.cpp

#include <QtGui>
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QLabel
lbl(QObject::tr("Hello"));
lbl.show();
return app.exec();
}

XML,
:
<!DOCTYPE TS><TS>
<context>
<name>QObject</name>
<message>
<source>Hello</source>
<translation type="unfinished"></translation>
</message>
</context>
</TS>

420

V.

" ". translation


type . ,
translation :
<translation></translation>

.
:
TRANSLATIONS = main_ru.ts main_de.ts

Qt Linguist
.
,
. , , " ", ,
. Qt Linguist Qt . .
,
. , . Qt Linguist (. 31.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 ( ) .

, , . ,
.
Phrases and guesses ( ) -

, , .

31.

421

. 31.2. Qt Linguist

Warnings () . -

, .
. File | Save ( | ).
TS- QM- (Messages file, ) . File | Release
( | ), , Save ().

lrelease.
,
QM-
lupdate, Qt Linguist lrelease.
lrelease, . .

V.

422

QM-.
(TS-), , QM-:
lrelease myproject.pro

QM- QTranslator.
QTranslator . QM-, QTranslator,
load(). QM- . , 31.2, , "Hello" (. 31.3).

. 31.3.

31.2. main.cpp

int main(int argc, char** argv)


{
QApplication app(argc, argv);
QTranslator translator;
ptranslator.load("main_ru.qm", ".");
app.installTranslator(&translator);
QLabel lbl(QObject::tr("Hello"));
lbl.show();
return app.exec();
}

31.2 QTranslator. load() main_ru.qm, . , . ,


, , , QM-
, . installTranslator()
QApplication . , Qt, , , , WebKit . . . QM- Qt
. translations. , , : Qt, :
31.3. Qt

QTranslator qtTranslator;
qtTranslator.load(QString(":/translations/qt_") +
QLocale::system().name());
qApp->installTranslation(&qtTranslator);

31.

423

QTranslator appTranslator;
appTranslator.load(QString(":/translations/app_") +
QLocale::system().name());
appTanslator.load("main_ru.qm", ".");
qApp->installTranslator(&appTranslator);

QM- , 31.3.
, .


.
, . . ,
QSettings . .
,
. ,
. ,
. ,
, ,
, ,
.
QSettings.
,
, . , . .
. .
, . , . . , , .
QCoreApplication::
installTranslator(), QEvent::LanguageChange,
, QObject. , . 31.4.
31.4.

void MyLabel::changeEvent(QEvent* pe)


{
if (pe->type() == QEvent::LanguageChange) {

V.

424
retranslateUi();
}
}
void MyLabel::retranslateUi()
{
setWindowTitle(tr("Current Language"));
setText(tr("Hello"));
}

31.4, ,
QWidget::hangeEvent(), 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(&translator);
}

, (,
),
. QLocate::system().
QLocate, name() "_".
, : "en_US".

ISO 639-1, ISO 3166-1.

. , :
QTranslator translator;
QString str = QLocale::system().name();
if (str == "en_US") {
translator.load("myprogram_us.qm","."); //
//
}

31.

425

else if (str == "de_CH") {


translator.load("myprogram_de.qm","."); //
//
}
else if (str == "ru") {
translator.load("myprogram_ru.qm","."); //
}
qApp->installTranslator(&translator);


, , . , ,
. , ,
Google Translte (http://translate.google.com), Yahoo BabelFish (http://babelfish.
yahoo.com), ,
.
. ,
.
, .
Qt Linguist. .

. 31.4. Pootle

426

V.

Pootle (http://translate.sourceforge.net),
, . 31.4, .
, . . ts,
po xlf. lconvert,
Qt.

4 . tr() QObject . -, lupdate , . -,


. , . , , : , , , , ,
. .
, lupdate, ts (TS-) C++.
" " Qt Linguist.
QM-.
lrelease.
QM- QTranslator load().

installTranslator() QCoreApplication.
, , .

32


(Menu)?
! (File)

.

,
. :
;
;
(), ;
.

Qt QMenu.
QMenu. .
( QAction, . 35).

. , ,
, hovered(),
- , .


,
. . 32.1 .
.
, , , (<Alt> ).
, , . . . , , , . QMenuBar
QMenuBar.

V.

428

. 32.1.

"" ,
, .
, About Qt ( Qt), , . 32.1, <Ctrl>+<Q>. "" . . 32.1.
32.1. ""

<Esc>

<Ctrl>+<Z>

<F1>

<Ctrl>+<X>

<Shift>+<F1>

<Ctrl>+<C>

<Ctrl>+<N>

<Ctrl>+<V>

<Ctrl>+<O>

<Ctrl>+<F4>


MDI-

<Ctrl>+<P>

<Ctrl>+<F6>



MDI-

<Ctrl>+<S>

<Shift>+<Ctrl>+<F6>



MDI-

, . ,
, ( ) <Alt>. , Exit () <Alt>+<E>
(. . 32.1).
"" :

32.

429

<Alt>;
, ;
. ,

About Qt ( Qt), Menu () <Alt>+<M>, <Alt>+<A>.


SubMenu () (. . 32.1) ,
, Test ().
, , .
, .
, .
. .
.
.
, .
, . .
. , ,
.
, , , . , , .
32.1 , . 32.1.
32.1. main.cpp

#include <QtGui>
#include "img4.xpm"
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("&CheckableItem");
pCheckableAction->setCheckable(true);
pCheckableAction->setChecked(true);

V.

430
pmnu->addAction(QPixmap(img4_xpm), "&IconItem");
QMenu* pmnuSubMenu = new QMenu("&SubMenu", pmnu);
pmnu->addMenu(pmnuSubMenu);
pmnuSubMenu->addAction("&Test");

QAction* pDisabledAction = pmnu->addAction("&DisabledItem");


pDisabledAction->setEnabled(false);
pmnu->addSeparator();
pmnu->addAction("&Exit", &app, SLOT(quit()));
mnuBar.addMenu(pmnu);
mnuBar.show();
return app.exec();
}

,
.
QMenu. , QMenuBar
pmnuBar , , QMenu pmnu (. 32.1).

addAction() . addAction()
QAction. , .
setCheckable() ( pCheckableAction) . setChecked() . true,
, "" .
addAction() . ,
, &.
,
, . , ,
. . "" .
About Qt ( Qt) <Ctrl>+<Q>.
, ,
aboutQt().
"" . 14.2.
addSeparator() .
(pDisableAction) ,

setEnabled().
addAction() .

32.

431


Qt () (Tear-off menu).
, , , (. 32.2). , , .

. 32.2.

32.2. main.cpp.

#include <QtGui>
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QMenuBar pmnuBar;
QMenu*
pmnu
= new QMenu("&Menu");
pmnu->setTearOffEnabled(true);
pmnu->addAction("Item&1");
pmnu->addAction("Item&2");
pmnu->addAction("Item&3");
pmnu->addAction("&Exit", &app, SLOT(quit()));
pmnuBar.addMenu(pmnu);
pmnuBar.show();
return app.exec();
}

( 32.2), setTearOffEnabled()
pmnu, true,
.

432

V.


.
, .
, , QMenu.
, QMenuBar. . 32.3 ,
. Red (),
Green () Blue (), .

. 32.3.

32.3. main.cpp.

#ifndef _ContextMenu_h_
#define _ContextMenu_h_
#include <QtGui>
// ======================================================================
class ContextMenu : public QTextEdit {
Q_OBJECT
private:
QMenu* m_pmnu;
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");

32.

433

connect(m_pmnu,
SIGNAL(triggered(QAction*)),
SLOT(slotActivated(QAction*))
);
}
public slots:
void slotActivated(QAction* pAction)
{
QString strColor = pAction->text().remove("&");
setHtml(QString("<BODY BGCOLOR=%1></BODY>").arg(strColor));
}
};
#endif

//_ContextMenu_h_

32.3, ContextMenu,
m_pmnu. addAction() .
connect() triggered(QAction*) slotActivated(QAction*).
.
. , ContextMenu
QTextEdit,
HTML QTextEdit::setHtml(). , &,
QString::remove().
strColor.

QWidget::contextMenuEvent() ()
, . exec() ,
globalPos() . QPoint,
.

, , .
: , , .
,
,
"" ,
, . ,
. , , , , , , .

33


Windows :
Windows:
?
: !
Windows: ?

,
. , .
.
:
;
;
.


, ,
. , ,
, . ,
, . :
,

.
, : Ok, Cancel () Apply ();
,

(. 8). ;
. -

, (. 11);
, , -

33.

435

;
Help (),

;
, , , -

Open... (...). , ,
;
.

;
, .

, ;
.

. , ,
. , ,
;
, -

, . , , <Alt>, .

QDialog
QDialog ,
Qt (. . 5.1).
, ,
QDialog, ,
. :
;
.

,
QDialog::setModal() QDialog::isModal() . true
, false .


. , , , . ,
.
.
,
, . exec(),
. QDialog::Accepted QDialog::Rejected, Ok

V.

436

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().


, . 33.1, . Press Me (
) (. . 33.1, ),
First Name () Last Name () (. . 33.1, ).
33.1. main.cpp

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

33.

437

int main(int argc, char** argv)


{
QApplication app(argc, argv);
StartDialog startDialog;
startDialog.show();
return app.exec();
}

. 33.1.

33.1 StartDialog, .
33.2. StartDialog.h

#ifndef _StartDialog_h_
#define _StartDialog_h_
#include <QtGui>
#include "InputDialog.h"
// ======================================================================
class StartDialog : public QPushButton {
Q_OBJECT
public:
StartDialog(QWidget* pwgt = 0) : QPushButton("Press Me", pwgt)
{
connect(this, SIGNAL(clicked()), SLOT(slotButtonClicked()));
}
public slots:
void slotButtonClicked()
{
InputDialog* pInputDialog = new InputDialog;
if (pInputDialog->exec() == QDialog::Accepted) {
QMessageBox::information(0,
"Information",
"First Name: "
+ pInputDialog->firstName()

V.

438

+ "\nLast Name: "


+ pInputDialog->lastName()
);
}
delete pInputDialog;
}
};
#endif

//_StartDialog_h_

StartDialog QPushButton. clicked()


connect() slotButtonClicked() ( 33.2). InputDialog, .

, , .
.

if .
exec()
. , Ok,
. , . . , .
33.3. InputDialog.h

#ifndef _InputDialog_h_
#define _InputDialog_h_
#include <QDialog>
class QLineEdit;
// ======================================================================
class InputDialog : public QDialog {
Q_OBJECT
private:
QLineEdit* m_ptxtFirstName;
QLineEdit* m_ptxtLastName;
public:
InputDialog(QWidget* pwgt = 0);
QString firstName() const;
QString lastName () const;
};
#endif

//_InputDialog_h_

QDialog,
33.3. InputDialog
m_ptxtFirstName m_ptxtLastName ,
: firstName() lastName().

33.

439

33.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
QLabel* plblLastName

= new QLabel("&First Name");


= new QLabel("&Last Name");

plblFirstName->setBuddy(m_ptxtFirstName);
plblLastName->setBuddy(m_ptxtLastName);
QPushButton* pcmdOk
= new QPushButton("&Ok");
QPushButton* pcmdCancel = new QPushButton("&Cancel");
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);
}

?,
.
, Qt::WindowTitleHint Qt::WindowSystemMenuHint. ,
( 33.4).
Cancel ().
clicked() Ok Cancel () accept() rejected()
. , exec()
Ok QDialog::Accepted, Cancel ()
QDialog::Rejected.
33.5. InputDialog.cpp. firstName()

QString InputDialog::firstName() const


{
return m_ptxtFirstName->text();
}

440

V.

firstName() ( 33.5).
33.6. InputDialog.cpp. lastName()

QString InputDialog::lastName() const


{
return m_ptxtLastName->text();
}

firstName() ( 33.6).


, , , . .
, Qt.
, . .
, , .


,
, , . QFileDialog
(. 33.2)
. , ,
. QFileDialog QDialog.
QFileDialog.
:
getOpenFileName() . -

QString,
(. . 33.2);
getOpenFileNames() .

QStringList, ;
getSaveFileName() .

QString;
getExistingDirectory() . -

QString, .
-,
, , .
getOpenFileName() (. . 33.2).
, , ( ),
. :
QString str = QFileDialog::getOpenFileName(0, "Open Dialog", "", "*.cpp *.h");

33.

441

. 33.2.

33.7 , getSaveFileName(),
.
33.7.

QPixmap pix(320, 200);


QString strFilter;
QString str =
QFileDialog::getSaveFileName(0,
tr("Save Pixmap"),
"Pixmap",
"*.png ;; *.jpg ;; *.bmp",
&strFilter
);
if (!str.isEmpty()) {
if (strFilter.contains("jpg")) {
pix.save(str, "JPG");
}
else if (strFilter.contains("bmp")) {
pix.save(str, "BMP");
}
else {
pix.save(str, "PNG");
}
}

, - . 33.7

V.

442

320 200 ( pix). strFormat,


. getSaveFileName().
: , "Save Pixmap",
"Pixmap", , ;;, . , . . ( strFilter).
str , ,
strFilter QString::contains()
.
QPixmap::save(). JPG BMP ,
PNG.
getExistingDirectory() (. 33.3). :
QString str = QFileDialog::getExistingDirectory(0, "Directory Dialog", "");

. 33.3.


,
(. 33.4).
QPrintDialog, QPrinter (. 24)
, . . . :
QPrinter printer;
QPrintDialog* pPrintDialog = new QPrintDialog(&printer);
if (pPrintDialog->exec() == QDialog::Accepted) {
//
}
delete pPrintDialog;

33.

443

. 33.4.


QColorDialog (. 33.5).
, getColor().

. 33.5.

V.

444

. . QColor.
, OK Cancel (),
isValid() QColor. true
, OK, Cancel (). :
QColor color = QColorDialog::getColor(blue);
if (!color.isValid()) {
// Cancel
}



, (. 33.6).
QFontDialog, QFontDialog.

. 33.6.

, , QFontDialog::getFont(). . true ,
OK, false.
QFont,
.
getFont() , . :
bool bOk;
QFont fnt = QFontDialog::getFont(&bOk);

33.

445

if (!bOk) {
// Cancel
}


. QInputDialog. ,
,
QLineEdit, , ? , , ,
.
QInputDialog :
getText() ;
getInteger() ;
getDouble() ;
getItem() .

, , ,
. .
getInteger() getDouble()
( ),
( 2 147 483 647) ( 2 147 483 647) . getText() ,
( ). getItem() (QStringList), ( ),
( ).
: , , OK
Cancel (), (. 5).

. 33.7.

, (. 33.7) :
bool bOk;
QString str = QInputDialog::getText(0,
"Input",

V.

446
"Name:",
QLineEdit::Normal,
"Tarja",
&bOk
);
if (!bOk) {
// Cancel
}

QLineEdit::Normal QLineEdit::Password,
.


- Qt
QProgressDialog, QDialog.
.
Cancel () .
canceled(), , .
, , ,
. , setMinimumDuration() .
setTotalSteps().
setProgress().

. 33.8.

, . 33.8, :
int
n
= 100000;
QProgressDialog* pprd =
new QProgressDialog("Proessing the data...", "&Cancel", 0, n);
pprd->setMinimumDuration(0);
pprd->setWindowTitle("Please Wait");
for (int i = 0; i < n; ++i) {
pprd->setValue(i);
qApp->processEvents();

33.

447

if (pprd->wasCanceled()) {
break;
}
}
pprd->setValue(n);
delete pprd;

QProgressDialog
.
Cancel (). ,
. , .
, (. 5).
setMinimumDuration() 0, ,
. setWindowTitle()
. , ,
for, setValue(), .
processEvents() , , , (. 14).
if wasCanceled() , Cancel (),
, .
reset(),
. ,
, setAutoReset() true. setAutoClose(),
true.


, . : Next () Back ().
,
, , .
QWizard
addPage(). QWizardPage, setTitle() , .
,
. 33.8
, (. . 33.9).
33.8.

class Wizard : public QWizard {


private:
QWizardPage* createPage(QWidget* pwgt, QString strTitle)

V.

448
{
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("<H1>Label 1</H1>"), "One"));
addPage(createPage(new QLabel("<H1>Label 2</H1>"), "Two"));
addPage(createPage(new QLabel("<H1>Label 3</H1>"), "Three"));
}
};

. 33.9.


,
,
QMessageBox. ,
. .

33.

449

, QmessageBox, . ,
.
QMessageBox ,
.
: , , . .
, . . .
.

. 33.10.

, . 33.10, :
QMessageBox* pmbx =
new QMessageBox(QMessageBox::Information,
"MessageBox",
"<b>A</b> <i>Simple</i> <u>Message</u>",
QMessageBox::Yes | QMessageBox::No |
QMessageBox::Cancel
);
int n = pmbx->exec();
delete pmbx;
if (n == QMessageBox::Yes) {
// Yes
}

.
, (. 33.1). , , HTML. , (. 33.2), , ,
OK.
Yes, No Cancel. ,
Cancel (). <Escape>

Cancel.
,
. exec() QMessageBox
. exec() , n. delete . if Yes ().

V.

450

, , , QMessageBox. setText(),
setButtonText(). setButtonText() , . 33.2, . setWindowTitle() .
setIcon() ,
, . 33.1. , ,
QPixmap setIconPixmap().
33.1.

NoIcon

Information

Warning

Critical

Question

33.2. QMessageBox

NoButton

No

YesAll

Ok

Abort

NoAll

Cancel

Retry

Escape

Yes

Ignore

Default


.
information()
, . 33.11:
QMessageBox::information(0, "Information", "Operation Complete");

, (. 33.2).


(. 33.12) warning() QMessageBox.

33.

. 33.11.

451

. 33.12.

:
int n = QMessageBox::warning(0,
"Warning",
"The text in the file has changed"
"\n Do you want to save the changes?",
QMessageBox::Yes | QMessageBox::No,
QMessageBox::Yes
);
if (n == QMessageBox::Yes) {
// Saving the changes!
}

warning() ( ), , .
( Yes No). , ( Yes).
<Escape>, warning() QMessageBox::Escape.
Yes ().


, -
(. 33.13).
critical(), , , . :
int n = QMessageBox::critical(0,
"Attention",
"This operation will make your "
"computer unusable, continue?",
QMessageBox::Yes | QMessageBox::No |
QMessageBox::Cancel
);
if (n == QMessageBox::Yes) {
// Do it!
}

V.

452

. 33.13.

. 33.14.


, , about() QMessageBox. , : , ,
. . (. 33.14). . , , .
QMessageBox::about(0, "About", "My Program Ver. 1.0");

About Qt
About Qt ( Qt) QMessageBox aboutQt(). . , .

. 33.15. About Q

33.

453

Qt. . 33.15, .
:
QMessageBox::aboutQt(0);


QErrorMessage,
QMessageBox, . .
showMessage(), . :
(new QErrorMessage(this))->showMessage("Write Error");

. 33.16, , ,
.
;
, . , . . .

. 33.16.

,
. ,
QDialog.
, . , , ,
.
: .
. . , .
. ,
, .

454

V.

. , , , ,
.
, . .
, , . .
, ,
, "" "", , "
?"

34


.
, , .
:
, ...
, , , .
.
.
" "

, . :
;
" ";
(Online Help).


, , , ,

, .
(tooltip) , , . , , .
,
- , . , , , .
,
. , , . , Cancel ()
. ,
setToolTip():
QPushButton* pcmd = new QPushButton("&Ok");
pcmd->setToolTip("Button");

V.

456

. 34.1.

. 34.2.

, setToolTip()
.
, (. 34.2).
QLabel ,
setToolTip().
34.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);
}
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);

34.

457

MyWidget mw;
mw.setFixedSize(70, 70);
mw.setToolTip("<H1>My Tool Tip</H1>");
mw.show();
return app.exec();
}


( 34.1). event(),
QEvent::ToolTip.
QHelpEvent, . toolTip().
, show(). - ,
hide() , 3 . MyWidget
. Qt::ToolTip. ( main()) MyWidget setToolTip().

" "
,
. Whats this ( )
.
, , ,
. ,
? . <Shift>+<F1>.
, . 34.3, . ? , .

. 34.3. Whats this

34.2. main.cpp

#include <QtGui>
int main(int argc, char** argv)

V.

458
{
QApplication app(argc, argv);

QLabel lbl("Please press the ?-Button",


0,
Qt::WindowTitleHint | Qt::WindowSystemMenuHint
| Qt::WindowContextHelpButtonHint
);
lbl.setWhatsThis("<I>This is the Label</I><BR><B>Class QLabel</B>");
lbl.show();
return app.exec();
}

34.2 .
, | ()
Qt::WindowContextHelpButtonHint ? (. 5).
Whats this (
) setWhatsThis(). 34.2, , setWhatsThis(), HTML.

(Online Help)
,
.
, Help () <F1>.
HTML, , , , ,
.
, HTML .

" " .
QTextBrowser , HTML. , . 34.4,
.
34.3. main.cpp

#include <QtGui>
#include "HelpBrowser.h"
int main (int argc, char** argv)
{
QApplication app(argc, argv);
HelpBrowser helpBrowser("doc", "index.htm");

34.

459

helpBrowser.resize(400, 300);
helpBrowser.show();
return app.exec();
}

. 34.4.

, 34.3, helpBrowser. ,
.
34.4. HelpBrowser.h

#ifndef _HelpBrowser_h_
#define _HelpBrowser_h_
#include <QtGui>
// ======================================================================
class HelpBrowser : public QWidget {
Q_OBJECT
public:
HelpBrowser(const QString& strPath,
const QString& strFileName,
QWidget* pwgt
= 0
) : QWidget(pwgt)
{
QPushButton* pcmdBack
= new QPushButton("<<");

V.

460

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);
}
};
#endif

//_HelpBrowser_h_

34.4, HelpBrowser, : pcmdBack, pcmdHome pcmdForward.


connect() clicked()
QTextBrowser: backward(), home() forward(). . connect()
backwardAvailable(bool) forwardAvailable(bool) QTextBrowser
setEnabled(bool) ( pcmdBack pcmdForward).
, , .
setSearchPath() ,
. setSource() .
(pvbxLayout) (phbxLayout) .

34.

461


. : ,
" " (Online Help).
,
, . ,
.
" " ,
.
. , , . .
HTML . QTextBrowser.

35

SDI- MDI-
,
.
IBM

, ,
. . , Qt ,
.

QMainWindow
QMainWindow , (. 35.1),
, ,
(. 32), , , .
, , . . .
, . 35.1, , , . , , .
. .
QMainWindow::menuBar()
:
QMenu* pmnuFile = new QMenu("&File");
pmnuFile->addAction("&Save");
...
menuBar()->addMenu(pmnuFile);

, :
File () : New (),

Open (), Save (), Print () Quit ();


Edit () : Cut (),

Copy (), Paste (), Undo (), Redo (), Find (), Replace () Delete ();
View () , -

. , Zoom () .

35. SDI- MDI-

463

, , ;
Help ()

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

. 35.1.

, QMainWindow::
centralWidget(), QWidget.
QMainWindows::setCentralWidget()
.
QMainWindow::statusBar() . ,
(. 35.1), , , . QSizeGrip. (QMainWindow) , . . .

QAction
QAction ,
. , , ,

464

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_xpm));
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 Bar)
. , , , , .
, ,
.
, , . Qt

35. SDI- MDI-

465

QToolBar, QToolBar.
, , , ,
.
,
addAction(), . , ( 35.1).

.
(. 34) . , .

,
.
QToolBar addWidget().
, . 35.2, .
. QMainWindow.

. 35.2.

35.1. MainWindow.h

#ifndef _MainWindow_h_
#define _MainWindow_h_
#include
#include
#include
#include
#include

<QtGui>
"img1.xpm"
"img2.xpm"
"img3.xpm"
"img4.xpm"

// ======================================================================
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());
}

V.

466
QToolBar* createToolBar()
{
QToolBar* ptb = new QToolBar("Linker ToolBar");
ptb->addAction(QPixmap(img1_xpm),
ptb->addAction(QPixmap(img2_xpm),
ptb->addSeparator();
ptb->addAction(QPixmap(img3_xpm),
ptb->addAction(QPixmap(img4_xpm),

"1", this, SLOT(slotNoImpl()));


"2", this, SLOT(slotNoImpl()));
"3", this, SLOT(slotNoImpl()));
"4", this, SLOT(slotNoImpl()));

return ptb;
}
public slots:
void slotNoImpl()
{
QMessageBox::information(0, "Message", "Not implemented");
}
};
#endif //_MainWindow_h_

MainWindow, 35.1, QMainWindow. addToolBar()


, createToolBar() MainWindow.
addToolBar()
. createToolBar()
addAction(), :
, XPM

(. 19). QPixmap;
( );
slotNoImpl(),

Not implemented ( ).
addSeparator().

.
, , ,
, . .
, .
QDockWidget. . 35.1 ,
. QMainWindow :
QDockWidget* pdock = new QDockWidget("MyDock", this);
QLabel*
plbl = new QLabel("Label in Dock", pdoc);
pdock->setWidget(plbl);
addDockWidget(Qt::LeftDockWidgetArea, pdock);

35. SDI- MDI-

467

( pdock)
, , MyDock. ( plbl)
setWidget().
QMainWindow::addDockWidget(). ,
, Qt::LeftDockWidgetArea, . . .
-,
setAllowedAreas(). , -
, . . ,
, :
pdock->setAllowedAreas(Qt::BottomDockWidgetArea
| Qt::TopDockWidgetArea
);

- "" . , . -, , . setFeatures(). , - ,
:
pdock->setFeatures(QDockWidget::DockWidgetMovable
| QDockWidget::DockWidgetFloatable
);


, ,
.
QStatusBar, QStatusar.
:
showMessage().

clearMessage(). showMessage()
,
. ;
(-

, ).
. , - ,
. ,
addWidget().
removeWidget();
, . -

,
, <Caps Lock>, <Num Lock>,
<Insert> . . addPermanentWidget(), .

V.

468

. 35.3 ,
.
35.2. MainWindow.h

#ifndef _MainWindow_h_
#define _MainWindow_h_
#include <QtGui>
// ======================================================================
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);
m_plblX = new QLabel(this);
m_plblY = new QLabel(this);
statusBar()->addWidget(m_plblY);
statusBar()->addWidget(m_plblX);
}
};
#endif //_MainWindow_h_

. 35.3. ,

35. SDI- MDI-

469

MainWindow QMainWindow. , m_plblX m_plblY. addWidget().


mouseMoveEvent().
x() y() ( pe).


(Splash Screen).
, , . .
Qt QSplashScreen. main() exec() . , 35.3, ,
(. 35.4).

. 35.4.

35.3. main.cpp

#include <QtGui>
// ---------------------------------------------------------------------void loadModules(QSplashScreen* psplash)
{
QTime time;
time.start();

V.

470
for (int i = 0; i < 100; ) {
if (time.elapsed() > 40) {
time.start();
++i;
}

psplash->showMessage("Loading modules: "


+ QString::number(i) + "%",
Qt::AlignHCenter | Qt::AlignBottom,
Qt::black
);
}
}
// ---------------------------------------------------------------------int main (int argc, char** argv)
{
QApplication app(argc, argv);
QSplashScreen splash(QPixmap("splash.png"));
splash.show();
QLabel lbl("<H1><CENTER>My Application<BR>"
"Is Ready!</CENTER></H1>"
);
loadModules(&splash);
splash.finish(&lbl);
lbl.resize(250, 250);
lbl.show();
return app.exec();
}

35.3 .
,
show(). QLabel ,
. loadModules() ,
, . QTime (. 38) ,
i 40 . showMessage(), , (. . 7.1),
(. . 17.1). finish() .
,
. , ,
.

35. SDI- MDI-

471

SDI- MDI-
, . SDI
(Single Document Interface, ), MDI (Multiple
Document Interface, ). SDI-
, ,
. MDI-
( QMdiArea), , .

SDI-
SDI- Windows Notepad ().
, 35.435.9, , .
. 35.5.

. 35.5. SDI-

35.4. DocWindow.h

#ifndef _DocWindow_h_
#define _DocWindow_h_
#include <QTextEdit>
// ======================================================================
class DocWindow: public QTextEdit {
Q_OBJECT
private:
QString m_strFileName;
public:
DocWindow(QWidget* pwgt = 0);
signals:
void changeWindowTitle(const QString&);
public slots:
void slotLoad

();

V.

472
void slotSave ();
void slotSaveAs();
};
#endif //_DocWindow_h_

DocWindow, QTextEdit, ( 35.4). m_strFileName,


. changeWindowTitle() , . slotLoad(),
slotSave() slotSaveAs() .
35.5. DocWindow.cpp. DocWindow

DocWindow::DocWindow(QWidget* pwgt/*=0*/) : QTextEdit(pwgt)


{
}

, 35.5,
.
35.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);
}
}

slotLoad(), 35.6,
QFileDialog::getOpenFileName(),
. , ,
Cancel (), .
QString::isEmpty(). getOpenFileName() , QFile, . QIODevice::ReadOnly QFile::open() ,
.
stream, .

35. SDI- MDI-

473

QTextStream::readAll(),
QString. setPlainText(). close(),
changeWindowTitle(),
DocWindow , .
35.7. DocWindow.cpp. slotSaveAs()

void DocWindow::slotSaveAs()
{
QString str = QFileDialog::getSaveFileName(0, m_strFileName);
if (!str.isEmpty()) {
m_strFileName = str;
slotSave();
}
}

35.7 slotSaveAs()
QFileDialog::getSaveFileName().
Cancel () ,
m_strFileName , , slotSave().
35.8. DocWindow.cpp. slotSave()

void DocWindow::slotSave()
{
if (m_strFileName.isEmpty()) {
slotSaveAs();
return;
}
QFile file(m_strFileName);
if (file.open(QIODevice::WriteOnly)) {
QTextStream(&file) << toPlainText();
file.close();
emit changeWindowTitle(m_strFileName);
}
}

, , . . , . ,
.
QFile ( 35.8).
open(), QIODevice::WriteOnly (, ,
). , , , .
, , -

V.

474

<< , toPlainText().
QFile::close() . , , DocWindow.
35.9. SDIProgram.h

#ifndef _SDIProgram_h_
#define _SDIProgram_h_
#include <QtGui>
#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())
);
pmnuFile->addSeparator();
pmnuFile->addAction("&Quit",
qApp,
SLOT(quit()),
QKeySequence("CTRL+Q")
);
pmnuHelp->addAction("&About",
this,
SLOT(slotAbout()),
Qt::Key_F1
);

35. SDI- MDI-

475

menuBar()->addMenu(pmnuFile);
menuBar()->addMenu(pmnuHelp);
setCentralWidget(pdoc);
connect(pdoc,
SIGNAL(changeWindowTitle(const QString&)),
SLOT(slotChangeWindowTitle(const QString&))
);
statusBar()->showMessage("Ready", 2000);
}
public slots:
void slotAbout()
{
QMessageBox::about(this, "Application", "SDI Example");
}
void slotChangeWindowTitle(const QString& str)
{
setWindowTitle(str);
}
};
#endif

//_SDIProgram_h_

SDIProgram QMainWindow.
File () ( pmnuFile), Help () (
pmnuHelp) ( pdoc). addAction()
. , , , . Open... (...) slotLoad(), Save
() slotSave(), SaveAs... ( ...)
slotSaveAs(). DocWindow. About ( ) slotAbout(), SDIProgram.
menuBar() ,
addMenu() File () Help ().
setCentralWidget() , . . .
changeWindowTitle(), , slotChangeWindowTitle(). showMessage(), , "Ready"
, ( 2 ).

MDI-
DI- . , -

V.

476

.
. ,
.

. 35.6. MDI-

, ,
QMdiArea (. 35.6). "" . tileSubWindows()
cascadeSubWindows(), , . QMdiArea::subWindowList() , QMdiSubWindow.
, . 35.7, ,
MDI-. DocWindow, SDI- (. 35.435.8).
35.10. MDIProgram.h

#ifndef _MDIProgram_h_
#define _MDIProgram_h_
#include <QMainWindow>

35. SDI- MDI-


class
class
class
class

QMenu;
QMdiArea;
QSignalMapper;
DocWindow;

// ======================================================================
class MDIProgram : public QMainWindow {
Q_OBJECT
private:
QMdiArea*
m_pma;
QMenu*
m_pmnuWindows;
QSignalMapper* m_psigMapper;
DocWindow* MDIProgram::createNewDoc();
public:
MDIProgram(QWidget* pwgt = 0);
private slots:
void slotChangeWindowTitle(const QString&);
private slots:
void slotNewDoc
(
);
void slotLoad
(
);
void slotSave
(
);
void slotSaveAs
(
);
void slotAbout
(
);
void slotWindows
(
);
void slotSetActiveSubWindow(QWidget*);
};
#endif //_MDIProgram_h_

. 35.7. MDI-

477

V.

478

MDIProgram, 35.10, , (m_pma), Windows ()


(m_pmnuWindows) (m_psigMapper).

QAction triggered() .
, . . .
QSignalMapper.

MDIProgram ,
slotWindows(), (slotLoad(), slotSave() slotSaveAs()), (slotNewDoc()), .
35.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));
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));
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");
pactSave->setWhatsThis("Save the file to disk");
pactSave->setIcon(QPixmap(filesave));
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);

35. SDI- MDI-

479

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_F1);
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);
}

MDIProgram ( 35.11)
, pactNew, pactOpen
pactSave . triggered()
MDIProgram. addAction() .
File | Quit ( | )
closeAllWindows(), .
MDI- QMdiArea.
,

V.

480

setHorizontalScrollBarPolicy() setVerticalScrollBarPolicy(),
Qt::ScrollBarAsNeeded,

, . setCentralWidget().
( m_psigMapper)
mapped() slotSetActiveSubWindow(),
MDIProgram. ,
slotSetActiveSubWindow().
(. 35.20).
showMessage(), ,
"Ready" 3 .
35.12. MDIProgram.cpp. slotNewDoc()

void MDIProgram::slotNewDoc()
{
createNewDoc()->show();
}

slotNewDoc(), 35.12,
.
35.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));
connect(pdoc,
SIGNAL(changeWindowTitle(const QString&)),
SLOT(slotChangeWindowTitle(const QString&))
);
return pdoc;
}

35.13 createNewDoc() DocWindow, addSubWindow() .


setAttribute() Qt::WA_DeleteOnClose, ,
.
setWindowTitle() .
setWindowIcon().
, , ,
changeWindowTitle() slotChangeWindowTitle().

35. SDI- MDI-

481

35.14. MDIProgram.cpp. slotChangeWindowTitle()

void MDIProgram::slotChangeWindowTitle(const QString& str)


{
qobject_cast<DocWindow*>(sender())->setWindowTitle(str);
}

slotChangeWindowTitle() private . DocWindow,


setWindowTitle() ,
( 35.14).
35.15. MDIProgram.cpp. slotLoad()

void MDIProgram::slotLoad()
{
DocWindow* pdoc = createNewDoc();
pdoc->slotLoad();
pdoc->show();
}

slotLoad() createNewDoc(),
, ,
( 35.15).
35.16. MDIProgram.cpp. slotSave()

void MDIProgram::slotSave()
{
DocWindow* pdoc = qobject_cast<DocWindow*>(m_pma->activeSubWindow());
if (pdoc) {
pdoc->slotSave();
}
}

slotSave() , , DocWindow ,
( 35.16).
35.17. MDIProgram.cpp. slotSaveAs()

void MDIProgram::slotSaveAs()
{
DocWindow* pdoc = qobject_cast<DocWindow*>(m_pma->activeSubWindow());
if (pdoc) {
pdoc->slotSaveAs();
}
}

slotSaveAs() slotSave() ( 35.16),


slotSaveAs() ( 35.17).

V.

482
35.18. MDIProgram.cpp. slotAbout()

void MDIProgram::slotAbout()
{
QMessageBox::about(this, "Application", "MDI Example");
}

slotAbout() ( 35.18).
35.19. MDIProgram.cpp. slotWindows()

void MDIProgram::slotWindows()
{
m_pmnuWindows->clear();
QAction* pact = m_pmnuWindows->addAction("&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));
}
}

MDI- SDI-
Windows (), ,
. , clear() ( 35.19).
Windows () Cascade () Tile
(). (
subWindowList()) , setEnabled(), . for . setCheckable() true
, , -

35. SDI- MDI-

483

. , , setChecked() .
, triggered() ( pact) map()
m_psigMapper. , mapped() (. . 35.11) , at(), setMapping().
35.20. MDIProgram.cpp. slotSetActiveSubWindow()

void MDIProgram::slotSetActiveSubWindow(QWidget* pwgt)


{
if (pwgt) {
m_pma->setActiveSubWindow(qobject_cast<QMdiSubWindow*>(pwgt));
}
}

slotSetActiveSubWindow() ,
. ,
, QMdiSubWindow
setActiveSubWindow().

SDI (Single Document Interface, ) MDI (Multiple Document Interface, ). MDI- SDI- , SDI , MDI-
, .
QMainWindow , , . ,
. QMdiArea
, MDI-. , , , , , . .
QAction , , . , .
. , , .
: ,
.
,
QSplashScreen. .

36

(Desktop)
,
, .


, ,
. , , . ,
.


(Notification area) . Windows
(. 36.1) (Taskbar Notification Area), " " (System Tray),
( KDE (. 36.2) GNOME
(. 36.3)), Mac OS X Menu Extras
(. 36.4). , .
.

. 36.1. Windows Vista

. 36.2. KDE/Linux

. 36.3. GNOME/Linux

. 36.4. Mac OS X Snow Leopard Lion

,
( ), ,
. , , , Skype ICQ, Windows
. , ,
. ,
, ,

36. (Desktop)

485


.
, ?
QSystemTrayIcon. . . , setIcon(),
show(). ,
showMessage().
setToolTip(), , , , . ,
, ,
.
setContextMenu().
.
, (. 36.5):
Show/Hide Application Window (/ ) -

. 36.6 . , ;
Show Message ( ) , . 36.7;
Change Icon ( ) -

;
Quit ().

, (. 36.8).

. 36.5.

. 36.6.

. 36.7.

. 36.8.

36.1. main.cpp

#include <QtGui>
#include "SystemTray.h"

V.

486
int main(int argc, char** argv)
{
QApplication app(argc, argv);
SystemTray
st;
QApplication::setQuitOnLastWindowClosed(false);
return app.exec();
}

, 36.1, .
, QApplication::setQuitOnLastWindow() false. Qt , , . ., , , ,
.
show().
36.2. SystemTray.h

#ifndef _SystemTray_h_
#define _SystemTray_h_
#include <QLabel>
class QSystemTrayIcon;
class QMenu;
// ======================================================================
class SystemTray : public QLabel {
Q_OBJECT
private:
QSystemTrayIcon* m_ptrayIcon;
QMenu*
m_ptrayIconMenu;
bool
m_bIconSwitcher;
protected:
virtual void closeEvent(QCloseEvent*);
public:
SystemTray(QWidget* pwgt = 0);
public slots:
void slotShowHide
();
void slotShowMessage();
void slotChangeIcon ();
};
#endif //_SystemTray_h_

36. (Desktop)

487

, 36.2,
. QLabel, .
:
QSystemTrayIcon ( m_ptrayIcon), -

;
QMenu ( m_ptrayIconMenu), -

;
m_bIconSwitcher, -

.
closeEvent(),
.
, slotShowHide(), slotShowMessage() slotChangeIcon(), .
36.3. SystemTray.cpp.

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


: QLabel("<H1>Application Window</H1>", 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("S&how Message", this);
connect(pactShowMessage, SIGNAL(triggered()),
this,
SLOT(slotShowMessage())
);
QAction* pactChangeIcon = new QAction("&Change Icon", this);
connect(pactChangeIcon, SIGNAL(triggered()),
this,
SLOT(slotChangeIcon())
);
QAction* pactQuit = new QAction("&Quit", this);
connect(pactQuit, SIGNAL(triggered()), qApp, SLOT(quit()));
m_ptrayIconMenu = new QMenu(this);
m_ptrayIconMenu->addAction(pactShowHide);
m_ptrayIconMenu->addAction(pactShowMessage);
m_ptrayIconMenu->addAction(pactChangeIcon);
m_ptrayIconMenu->addAction(pactQuit);

V.

488
m_ptrayIcon = new QSystemTrayIcon(this);
m_ptrayIcon->setContextMenu(m_ptrayIconMenu);
m_ptrayIcon->setToolTip("System Tray");
slotChangeIcon();
m_ptrayIcon->show();
}

( 36.3) (QAction)
. ( QMenu)
. (QSystemTrayIcon), this.
setContextMenu() .
setToolTip() "System Tray".
slotChangeIcon(), . , show() .
36.4. SystemTray.cpp. closeEvent()

/*virtual*/void SystemTray::closeEvent(QCloseEvent* pe)


{
if (m_ptrayIcon->isVisible()) {
hide();
}
}

, , ,
.
( 36.4). , ,
, hide(), .
36.5. SystemTray.cpp. slotShowHide()

void SystemTray::slotShowHide()
{
setVisible(!isVisible());
}

slotShowHide(), 36.5, Show/Hide


Application Window. . , , , .
36.6. SystemTray.cpp. slotShowMessage()

void SystemTray::slotShowMessage()
{
m_ptrayIcon->showMessage("For your information",
"You have selected the "

36. (Desktop)

489

"\"Show Message!\" option",


QSystemTrayIcon::Information,
3000
);
}

slotShowMessage() Show Message.


showMessage() (. 36.6). , , , , ,
, 3 .
36.7. SystemTray.cpp. slotChangeIcon()

void SystemTray::slotChangeIcon()
{
m_bIconSwitcher = !m_bIconSwitcher;
QString strPixmapName = m_bIconSwitcher ? ":/images/img1.bmp"
: ":/images/img2.bmp";
m_ptrayIcon->setIcon(QPixmap(strPixmapName));
}

slotChangeIcon() Change Icon


. m_bIconSwitcher , ,
img1.bmp img2.bmp.
setIcon().


QDesktopWidget .
,
,
. , ,
.
desktop(), 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
);

V.

490

, ,
, .
, ,
, , , .
numScreens() ;
primaryScreen() , -

;
isVirtualDesktop() . -

, ,
;
screenNumber() ( QPoint) -

, . :
int nScreen = desktopWidget->screenNumber(QPoint(320, 115));

, QDesktopWidget::screenGeometry()
width() height() .
:
QDesktopWidget*
for (int i = 0;
qDebug() <<
qDebug() <<
qDebug() <<
}

pwgt = QApplication::desktop();
i < pwgt->numScreens(); ++i) {
"Screen:" << i;
"width:" << pwgt->screenGeometry(i).width();
"height:" << pwgt->screenGeometry(i).height();

, QDesktopWidget
resized() ,
screenCountChanged().
.
(. 36.9), Capture Screen
.
36.8. main.cpp

#include <QtGui>
#include "GrabWidget.h"
int main(int argc, char** argv)
{
QApplication app(argc, argv);
GrabWidget
wgt;
wgt.show();
return app.exec();
}

36. (Desktop)

491

. 36.9. ,

( 36.8) 36.9
36.11 GrabWidget, .
36.9. GrabWidget.h

#ifndef _GrabWidget_h_
#define _GrabWidget_h_
#include <QWidget>
class QLabel;
// ======================================================================
class GrabWidget : public QWidget {
Q_OBJECT
private:
QLabel* m_plbl;
public:
GrabWidget(QWidget* pwgt = 0);

V.

492
public slots:
void slotGrabScreen();
};
#endif //_GrabWidget_h_

GrabWidget ( 36.9)
(m_plbl), "" . slotGrabScreen(),
.
36.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);
}

, 36.10, Capture
Screen ( ) ( clicked()) (slotGrabScreen()). pvbxLayout.
36.11. GrabWidget.cpp. slotGrabScreen()

void GrabWidget::slotGrabScreen()
{
QDesktopWidget* pwgt = QApplication::desktop();
QPixmap
pic = QPixmap::grabWindow(pwgt->screen()->winId());
m_plbl->setPixmap(pic.scaled(m_plbl->size()));
}

36.11 , , , .
, desktop(). QPixmap , grabWindow() , , , winId().

36. (Desktop)

493

grabWindow() ,
. , . screen(),
, , , , . ,
.

,
QDesktopWidget::numScreens().

:
( scaled()),
setPixmap().


QDesktopServices.
, , , ,
, , , . . storageLocation() ,
QDesktopServices::MoviesLocation.

Web- .
Web- , , :
bool bRes = QDesktopServices::openUrl(QUrl("http://www.bhv.ru"));
qDebug() << "Result:" << bRes;

( Windows )
, , , . QSystemTrayIcon.
QDesktopWidget. .
QDesktopServices
Web-.

494

V.

VI

Qt
, . ,
.
, .

37.

, -

38.

39.

40.

41.

XML

42.

43.

44.

Qt API

45.

Qt Designer.

46.

47.

WebKit

48.

Qt Creator

49.

Qt3 Qt4

37

,
-

, , .

, . (
, Windows) , , Qt
, :
QDir ;
QFile ;
QFileInfo ;
QIODevice -;
QBuffer .

-. QIODevice
QIODevice , -,
-,
.
. Qt , QIODevice (. 37.1):
QFile ;
QBuffer ,
QByteArray, ;

QAbstractSocket (.

40);
QProcess , -

(. 39) , QIODevice;
,
QIODevice:

VI. Qt

498

. 37.1. -

QIODevice::NotOpen ( -

open());
QIODevice::ReadOnly

;
QIODevice::WriteOnly

;
QIODevice::ReadWrite -

( , ReadOnly | WriteOnly);
QIODevice::Append -

;
QIODevice::Unbuffered ,

;
QIODevice::Text -

. Windows "\r\n", MacOS X


Unix "\r";
QIODevice::Truncate , ,

.
, , openMode().
read() write().
readAll(),
QByteArray. readLine() getChar() .
QIODevice seek(). pos(). , . ,
, . ,
size(), .
QFile, QBuffer QTemporaryFile.
-, Qt , QIODevice
readData() writeData().
open(), close() atEnd().
QIODevice ,
, , . ,
:

37. , -

499

void print(QIODevice* pdev)


{
char
ch;
QString str;
pdev->open(QIODevice::ReadOnly);
for (; !pdev->atEnd();) {
pdev->getChar(&ch);
str += ch;
}
pdev->close();
qDebug() << str;
}

QIODevice , -. ,
, , , .
, ,
isReadable() isWriteable().

. QFile
QFile QIODevice (. . 37.1).
: , , . ,
, .
, setName(). :
QFile file;
file.setName("file.dat");

, . QIODevice::isOpen(), true, ,
false. , close(). .
, QFile::flush().
, , QFile::exists().
, .
, true, false. QFile::exists(),
, fileName(). QIODevice::read()
QIODevice::write() .
:
QFile file1("file1.dat");
QFile file2("file2.dat ");
if (file2.exists()) {
// . ?
}
if (!file1.open(QIODevice::ReadOnly)) {
qDebug() << " ";
}

VI. Qt

500
if (!file2.open(QIODevice::WriteOnly)) {
qDebug() << " ";
}
char a[1024];
while(!file1.atEnd()) {
int nBlocksize = file1.read(a, sizeof(a));
file2.write(a, nBlocksize);
}
file1.close();
file2.close();

,
QIODevice::write() QIODevice::readAll().
QByteArray, :
QFile file1("file1.dat");
QFile file2("file2.dat");
if (file2.exists()) {
// . ?
}
if (!file1.open(QIODevice::ReadOnly)) {
qDebug() << " ";
}
if (!file2.open(QIODevice::WriteOnly)) {
qDebug() << " ";
}
QByteArray a = file1.readAll();
file2.write(a);
file1.close();
file2.close();



, , , . ,
. qCompress()
qUncompress(), QByteArray. QByteArray
QByteArray.

QFile remove(). , .

QBuffer
QBuffer QIODevice (. . 37.1) (memory mapped files). (
open() close()). write()

37. , -

501

read() .

, , :
QByteArray arr;
QBuffer
buffer(&arr);
buffer.open(QIODevice::WriteOnly);
QDataStream out(&buffer);
out << QString("Message");

, QByteArray.
buffer()
QByteArray, setBuffer() QByteArray
.
data() buffer(), setData() setBuffer()
, QByteArray, .
QBuffer . ,
QBuffer, , , .

QTemporaryFile
. , ,
- .
QTemporaryFile .
, ,
, . ,
QDir::tempPath(). .

. QDir
. Windows
, : :\Windows\System. UNIX /, : /usr/bin. , .
Qt QDir.
, :
QDir::current() ;
QDir::root() ;
QDir::drives() QFileInfo,

( Windows C:\, D:\ . .);


QDir::home() .

VI. Qt

502


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().
, . 37.2,
, Directory ().
. Mask
() . ,
C++ Mask () *.cpp *.h.
Find () . .
37.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*
QLabel*
QPushButton*
QPushButton*

plblDir
plblMask
pcmdDir
pcmdFind

=
=
=
=

new
new
new
new

QLabel("&Directory");
QLabel("&Mask");
QPushButton(QPixmap(fileopen), "");
QPushButton("&Find");

37. , -

503

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);
}

. 37.2.

FileFinder, 37.1,
( m_ptxtDir, m_ptxtMask
m_ptxtResult). , QDir::absolutePath(), , , , QDir::current().
, .
( pcmdFind
pcmdDir), slotFind() slotBrowse().
setBuddy() .
QGridLayout (. 6).

VI. Qt

504
37.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);
}
}

37.2 slotBrowse(), . Directory () setText().


37.3. FileFinder.cpp. slotFind()

void FileFinder::slotFind()
{
start(QDir(m_ptxtDir->text()));
}

slotFind() , start() ( 37.3).


37.4. FileFinder.cpp. start()

void FileFinder::start(const QDir& dir)


{
QApplication::processEvents();
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)));
}
}

37. , -

505

start() ( 37.4).
, "" .
QApplication::processEvent() . start() listFiles
, . . ,
.
, QString::split().
( QDir::Files) , .

append(). entryList()
QDir::Dirs . ,
"." "..", start().

37.4 QDir::NoDotAndDotDot "." "..".

entryList() .
setFilter(). , setSorting(). , :
dir.setFilter(QDir::Files | QDir::Hidden);
dir.setSorting(QDir::Size);
QStringList content = dir.entryList();

. QFileInfo
QFileInfo : , , , . . QFile.

?
, , ,
. isFile() isDir().
, isFile() true, false.
, isDir() true, false. ,
QFileInfo isSymLink(), true,
( "symbolic link" UNIX, Windows
(shortcut)).

UNIX . ln s.

VI. Qt

506

absoluteFilePath(),
filePath(). fileName(), -

. , baseName(). completeSuffix().


, .
QFileInfo created(), lastModified() lastRead()
. QDateTime (. 38),
toString(). :
//
fileInfo.created().toString();
//
fileInfo.lastModified().toString();
//
fileInfo.lastRead().toString();


, .
QFileInfo :
isReadable() true, -

;
isWriteable() true,

;
isHidden() true, ;
isExecutable() true, .

UNIX , DOS
Windows, .


size() QFileInfo .
, , . , K, M,
G, T. , ( ,
):
QString fileSize(qint64 nSize)
{
int i = 0;

37. , -

507

for (; nSize > 1023; nSize /= 1024, ++i) {


if(i >= 4) {
break;
}
}
return QString().setNum(nSize) + "BKMGT"[i];
}


, . ,
. , . , .
QFileSystemWatcher. ,
addPath() , , removePath().
fileChanged(),
directoryChanged(). , . . ,
(. 37.3).

. 37.3. ,


37.5. Viewer.h

#ifndef _Viewer_h_
#define _Viewer_h_
#include <QTextEdit>
// ======================================================================
class Viewer : public QTextEdit {
Q_OBJECT

508

VI. Qt

public:
Viewer(QWidget* pwgt = 0);
private slots:
void slotDirectoryChanged(const QString&);
void slotFileChanged
(const QString&);
};
#endif //_Viewer_h_

. QTextEdit slotDirectory()
slotFileChaged() (. . 37.5).
37.6. Viewer.cpp

#include "Viewer.h"
// ---------------------------------------------------------------------Viewer::Viewer(QWidget* pwgt /*=0*/) : QTextEdit(pwgt)
{
setWindowTitle("File System Watcher");
}
// ---------------------------------------------------------------------void Viewer::slotDirectoryChanged(const QString& str)
{
append("Directory changed:" + str);
}
// ---------------------------------------------------------------------void Viewer::slotFileChanged(const QString& str)
{
append("File changed:" + str);
}

( 37.6).
append()
slotDirectoryChanged() slotFileChanged().
37.7. main.cpp

#include <QtGui>
#include "Viewer.h"
int main(int argc, char** argv)
{
QApplication
app(argc, argv);
QFileSystemWatcher watcher;
Viewer
viewer;

37. , -

509

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 QString&)),
&viewer, SLOT(slotDirectoryChanged(const QString&))
);
QObject::connect(&watcher, SIGNAL(fileChanged(const QString&)),
&viewer, SLOT(slotFileChanged(const QString&))
);
return app.exec();
}

37.7 (watcher)
(viewer). (app) , ( arguments()).
, . . . QFileSystemWatcher::addPaths().
, , . , ( QFileSystemWatcher::files()) ( QFileSystemWatcher::
directories()). QFileSystemWatcher::
directoryChanged() QFileSystemWatcher::fileChanged() slotDirectoryChanged()
slotFileChanged() .

-

. . , ,
QTextStream, QDataStream.
QTextStream QDataStream , C++ (iostream), ,
QIODevice.
, QIODevice.
<<, >>.

QTextStream
QTextStream . , ,
QIODevice, char, QChar, char*, QString, QByteArray, short, int, long,

VI. Qt

510

float double. , ,

QTextStream::setRealNumberPrecision() .

Unicode.
, QFile
QTextStream::readLine(). :
QFile file("file.txt");
if (file.open(QIODevice::ReadOnly)) {
QTextStream stream(&file);
QString str;
while (!stream.atEnd()) {
str = stream.readLine();
qDebug() << str;
}
if (stream.status() != QTextStream::Ok) {
qDebug() << " ";
}
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(&file);
stream << str.toUpper(); // THIS IS A TEST
file.close();
if (stream.status() != QTextStream::Ok) {
qDebug() << " ";
}
}

QTextStream , . QDataStream.

37. , -

511

QDataStream
QDataStream , , ,
. (. 40). , QDataStream,
Qt .
, , Qt,
setVersion(), .
Qt_4_5.
, , :
QByteArray, QFont, QImage, QMap, QPixmap, QString, QValueList Variant.
(QPointF), ,
(QImage):
QFile file("file.bin");
if(file.open(QIODevice::WriteOnly)) {
QDataStream stream(&file);
stream.setVersion(QDataStream::Qt_4_5);
stream << QPointF(30, 30) << QImage("image.png");
if (stream.status() != QDataStream::Ok) {
qDebug() << " ";
}
}
file.close();

:
QPointF pt;
QImage img;
QFile
file("file.bin");
if(file.open(QIODevice::ReadOnly)) {
QDataStream stream(&file);
stream.setVersion(QDataStream::Qt_4_5);
stream >> pt >> img;
if (stream.status() != QDataStream::Ok) {
qDebug() << " ";
}
}
file.close();

Qt QIODevice, . , QIODevice, . QFile QBuffer .

VI. Qt

512

QFile , , ,
, .
QBuffer . , ,
.
QDir .
,
, .
QFileInfo
.

Qt

QFileSystemWatcher.

Qt , : QDataStream QTextStream .
C++.
, << >>.
, QIODevice, QFile
, , QBuffer.

38

,
, .
.

,
.


, , . Qt : QDate, QTime QDateTime, QDate,
QTime QDateTime.

QDate
QDate
. QDate . , , . ,
, 25 2009 :
QDate date(2009, 10, 25);

setDate() .
:
QDate date;
date.setDate(2009, 10, 25);

, , , :
year() 1752 8000;
month() 1 12 ( -

);
day() 1 31.

daysInMonth() ,
daysInYear() .

VI. Qt

514

dayOfWeek().
dayOfYear(). ,
weekNumber().
toString() , , . 38.1.
38.1. DateFormat Qt

TextDate

0x0000

Qt ( )

ISODate

0x0001

ISO 8601 (YYYY-MM-DD)

SystemLocaleDate

0x0002

LocaleDate

0x0003

, ,
QLocale::setDefault().
,
SystemLocaleDate

, ,
toString() -, . :
QDate date(2009, 7, 3);
QString str;
str = date.toString("d.M.yy");
//str
str = date.toString("dd/MM/yy");
//str
str = date.toString("yyyy.MMM.ddd"); //str
str = date.toString("yyyy.MMMM.dddd");//str

=
=
=
=

"3.7.09"
"03/07/09"
"2009.."
"2009.."

addDays() ,
. addMonths() addYears() ,
, . :
QDate date(2009, 1, 3);
QDate date2 = date.addDays(-7);
QString str = date2.toString("dd/MM/yy"); //str = "27/06/09"

QDate fromString(), QDate.


,
. 38.1 .
. currentDate(), QDate.
daysTo() . :
QDate dateToday = QDate::currentDate();
QDate dateNewYear(dateToday.year(), 12, 31);
qDebug() << " "
<< dateToday.daysTo(dateNewYear)
<< " ";

38. ,

515

, QDate ==, !=, <, <=, > >=. :


QDate date1(2009, 1, 3);
QDate date2(2009, 1, 5);
bool b = (date1 == 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()
. , , ,
. 38.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. , . , . 38.1, .


, ( )
. addSecs() addMSecs().
QTime currentTime().
start() , ,
, elapsed(). ,

516

VI. Qt

, . . ,
. test():
QTime time;
time.start();
test();
qDebug() << " test() "
<< time.elapsed()
<< " "
<< endl;

QTime 24- , . QDateTime.

QDateTime
QDateTime . date()
(QDate), time() (QTime).
toString() .
, . 38.1,
.


. ,
QTime
:
QTime time;
time.start();
for(;time.elapsed() < 1000;) {
}
function();

. . -
, , ,
, . . "".
, processEvents()
QApplication, ,
. :
QTime time;
time.start();
for(;time.elapsed() < 1000;) {
qApp->processEvents();
}

38. ,

517

: , . .
, , .
. , . , .
, . .
, .
(firing interval).
, .
, , , ,
. Windows 98 55 , OC, Qt, 1 . , , , (. 38.5).
, , ,
, , 24 .
.
. ,
(. 39), ,
. , . , , . .
.
(. 39)
, (event loop).
QThread::exec().


, QObject, . QObject::startTimer() . . startTimer() ,
, . QTimerEvent,
timerEvent(). QTimerEvent::timerId() QTimerEvent,
, . , QObject::killTimer(). , . 38.1, , .

. 38.1.

VI. Qt

518
38.1. main.cpp. main()

int main (int argc, char** argv)


{
QApplication app (argc, argv);
BlinkLabel
lbl("<FONT COLOR = RED><CENTER>Blink</CENTER></FONT>");
lbl.show();
return app.exec();
}

main() BlinkLabel, HTML ( 38.1).


38.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_bBlink ? m_strText : "");
}
public:
BlinkLabel(const QString& strText,
int
nInterval = 200,
QWidget* pwgt
= 0
)
: QLabel(strText, pwgt)
, m_bBlink(true)
, m_strText(strText)
{
startTimer(nInterval);
}
};

BlinkLabel, 38.2, m_bBlink,


, m_strText, .
BlinkLabel nInterval.
200 . startTimer() . QTimerEvent, timerEvent(), m_bBlink -

38. ,

519

. setText() :
false ;
true .

QTimer
QTimer , ,
QObject. , QObject. , . , , , .
Qt QTimer, QObject. ,
QTimer, start(). .
QTimer singleShot()
( singleshot).
QTimer. , , .
. , , - 5
( 38.3).
38.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() .
, .
, -

VI. Qt

520

, , ,
,
. delay(), ,
.
38.4.

void delay(int n)
{
QEventLoop loop;
QTimer::singleShot(n, &loop, SLOT(quit()));
loop.exec();
}

38.4 QEventLoop,
. exec() . , singleShot(), n,
quit() ( loop).
, . 38.2, ,
. .

. 38.2.

38.5. Clock.h

#ifndef _Clock_h_
#define _Clock_h_
#include <QtGui>
// ======================================================================
class Clock : public QLabel {
Q_OBJECT
public:
Clock(QWidget* pwgt = 0) : QLabel(pwgt)
{
QTimer* ptimer = new QTimer(this);
connect(ptimer, SIGNAL(timeout()), SLOT(slotUpdateDateTime()));
ptimer->start(500);
slotUpdateDateTime();
}

38. ,

521

public slots:
void slotUpdateDateTime()
{
QString str =
QDateTime::currentDateTime().toString(Qt::SystemLocaleDate);
setText("<H2><CENTER>" + str + "</CENTER></H2>");
}
};
#endif //_Clock_h_

38.5, Clock, ( ptimer).


timeout() slotUpdateDateTime(), . start() . . slotUpdateDateTime()
currentDateTime(). ,
Qt::SystemLocaleDate (. . 38.1), setText() .

QBasicTimer
Qt QBasicTimer, : isActive(),
start(), stop() timerId(),
QTimer. start(). ,
,
QObject, . , , QObject,
QObject::timerEvent().

QDate, QTime QDateTime , . .


.
.
.
. ,
, -
. .
, , .
.

39


... .

.
, , . Qt, .
.
, , ,
. .

, ,
. ,
.
, ,
. ,
, . , .
, , , .
,
. ,
.
Qt- .
QProcess, QProcess.
, IODevice (. 37),
, ,
. , QProcess
.
, -

39.

523

, . QProcess . , error()
.
.
start(), ,
. , started(), finished().
finished() . exitStatus(), :
NormalExit ( ) CrashExit ( ).
QProcess
: (stdout) (stderr).
setReadChannel(). , readyRead(). : readyReadStandardOutput()
readyReadStandardError()

QIODevice:
write(), read(), readLine() getChar(). ,

:
readAllStandardOutput()

readAllStandardError(). QByteArray.
, . 39.1,
QProcess. Command ()
, .
, .

. 39.1.

VI. Qt

524
39.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("&Enter");
connect(m_process,
SIGNAL(readyReadStandardOutput()),
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->readAllStandardOutput());
}

39.

525

// -----------------------------------------------------------------void slotReturnPressed()
{
QString strCommand = "";
#ifdef Q_WS_WIN
strCommand = "cmd /C ";
#endif
strCommand += m_ptxtCommand->text();
m_process->start(strCommand);
}
};

Shell QProcess ( 39.1).


readyReadStandardOutput() slotDataOnStdout(), readAllStandardOutput() .
m_ptxtDisplay append().
slotReturnPressed() clicked() ( pcmd) returnPressed() ( m_txtCommand). Windows, dir, ,
cmd.
Windows cmd /C.

, . start().

, , startDetached().

start() ;
, waitForStarted() waitForFinished(). ,
, , . :
QProcess proc;
proc.start("cmd /k " + strProgram);
proc.waitForStarted();

.
Qt QThread. , .
,
, .
, ( ). ,
. , -

526

VI. Qt

, , . , , .
.
,
,
, . ,
, . . . ,
(dual core), .
, ,
, . ,
, , , , .
, . .
.
, . , , .

. , ,
. . , , , . , , , , . , ,
, .
, , . ,
, Qt.
.
- ?
QThread run(), , . :
class MyThread : public QThread {
public:
void run()
{
// ,
}
}

start(),
, , run().

39.

527

:
MyThread thread;
thread.start();

, , . :
.

IdlePriority, LowestPriority, LowPriority,


NormalPriority. ,
, - ;
HighPriority HighestPriority. -

.
- ;
TimeCriticalPriority. -

.
, , .
, start(). :
MyThread thread;
thread.start(QThread::IdlePriority);

, ,
priority().
setPriority().
!
Linux ,
100 . ,
. Windows : , , ,
, ,
- , .


. , , , ,
?
(. 39.2).
. : .

VI. Qt

528

. 39.2.


- ,
.

, , , .
QTimer (. 38) (. 40).
,
exec() run(). quit() exit(). ,
main().
QObject , . , QObject, ,
. QObject::thread(). . , .
, . .
, .
QObject::moveToThread().

-
,
. 2 , connect()
.
Qt::AutoConnection, . , Qt ,
. , -

39.

529

. , , . Qt , , ,
, . , , . , , .
, . 39.3, . 10 0, .

. 39.3. -

39.2. main.cpp. MyThread

class MyThread : public QThread {


Q_OBJECT
private:
int m_nValue;
public:
MyThread() : m_nValue(10)
{
}
void run()
{
QTimer timer;
connect(&timer, SIGNAL(timeout()), SLOT(slotNextValue()));
timer.start(1000);
exec();
}
signals:
void finished
(
);
void currentValue(int);
public slots:
void slotNextValue()
{
emit currentValue(--m_nValue);

VI. Qt

530
if (!m_nValue) {
emit finished();
}
}
};

MyThread . QThread run(). , Q_OBJECT,


. m_nValue
( 39.2). run(), , .
timeout()
slotNextValue(),
exec().
, ( timer) , , new: run() ,
. exec() ,
run(), . main(), , QApplication::exec()
,
Qt- .
C slotNextValue() m_nValue currentValue() . ,
finished(), .
39.3. main.cpp. main()

int main(int argc, char** argv)


{
QApplication app(argc, argv);
QLCDNumber
lcd;
MyThread
thread;
QObject::connect(&thread,
&lcd,
);
QObject::connect(&thread,
&app,
);

SIGNAL(currentValue(int)),
SLOT(display(int))
SIGNAL(finished()),
SLOT(quit())

lcd.setSegmentStyle(QLCDNumber::Filled);
lcd.display(10);
lcd.resize(220, 90);
lcd.show();
thread.start();

39.

531

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

39.3 , lcd thread. , , currentValue() display().


finished() quit() ,
. ,
, start().
, main.cpp, , MOC include, 39.3.
, . ,
, run() ( 39.2) ( main()). run() :
void run()
{
exec();
}

main(), 39.3, :
QTimer timer;
QObject::connect(&timer, SIGNAL(timeout()),
&thread, SLOT(slotNextValue())
);
timer.start(1000);

, ,
.
. , , .
, . , . , . 39.4, ,
.

. 39.4. ,

39.4. main.cpp. MyThread

class MyThread : public QThread {


Q_OBJECT

VI. Qt

532
public:
void run()
{
for (int i = 0; i <= 100; ++i) {
usleep(100000);
emit progress(i);
}
}
signals:
void progress(int);
};

run(), 39.4,
0 100, 10 progress() . 10 QThread::usleep(),
.
39.5. main.cpp. main()

int main(int argc, char** argv)


{
QApplication app(argc, argv);
QProgressBar prb;
MyThread
thread;
QObject::connect(&thread, SIGNAL(progress(int)),
&prb,
SLOT(setValue(int))
);
prb.show();
thread.start();
return app.exec();
}
#include "main.moc"

39.5
thread, progress() , , setValue() . start().


. 16, :
QCoreApplication::postEvent() QCoreApplication::sendEvent().
, : postEvent() -

39.

533

, sendEvent() .
postEvent(). . 39.5 ,
. , , ,
. . , , , .

. 39.5.

,
QObject::event().
, ,
.
, , . 39.4.
39.6. 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;
}
};

, , ,
( 39.6). QEvent

VI. Qt

534

m_nValue.
value() setValue(). ,
QEvent().
39.7. main.cpp. MyThread

class MyThread : public QThread {


private:
QObject* m_pobjReceiver;
public:
MyThread(QObject* pobjReceiver) : m_pobjReceiver(pobjReceiver)
{
}
void run()
{
for (int i = 0; i <= 100; ++i) {
usleep(100000);
ProgressEvent* pe = new ProgressEvent;
pe->setValue(i);
QApplication::postEvent(m_pobjReceiver, pe);
}
}
};

39.7 MyThread ,
39.4. , , -,
, - , , ,
- postEvent(). run() (memory leak), , . . .

, , ,
. . .
, . . - QObject::
connect(). , , . (. 39.4).
39.8. main.cpp. MyProgressBar

class MyProgressBar : public QProgressBar {


public:
MyProgressBar(QWidget* pwgt = 0) : QProgressBar(pwgt)
{
}

39.

535

void customEvent(QEvent* pe)


{
if ((int)pe->type() == ProgressEvent::ProgressType) {
setValue(((ProgressEvent*)(pe))->value());
}
QWidget::customEvent(pe);
}
};


, . (. 15).
customEvent().
39.8. customEvent() ,
ProgressType, ProgressEvent,
value().
QProgressBar::setValue() .
39.9. main.cpp. main()

int main(int argc, char** argv)


{
QApplication app(argc, argv);
MyProgressBar prb;
MyThread
thread(&prb);
prb.show();
thread.start();
return app.exec();
}

, 39.9, , start().
(. 39.4 39.5)
(. 39.639.9), ,
. , , .
, . ,
.

,
. , , . .
. , ,
. :
, - ,
. , -

VI. Qt

536

, , , .
, , .
.
(critical sections), . , , ,
. , , ,
. , ,
, .

(mutex) , ,
. ,
, , , .
, . , . - , , . . . ,
, . ,
, , . .

,
, .

, ,
. QMutex. lock() QMutex
. unlock(), .
QMutex tryLock(). ,
, . , false, , .
true, ,
.
, (thread safety).
39.10.

class ThreadSafeStringStack {
private:
QMutex
m_mutex;
QStack<QString> m_stackString;

39.

537

public:
void push(const QString& str)
{
m_mutex.lock();
m_stackString.push(str);
m_mutex.unlock();
}
QString pop(const QString& str)
{
QMutexLocker locker(&m_mutex);
return m_stackString.empty() ? QString()
: m_stackString.pop();
}
};

ThreadSafeStringStack, 39.10, ,
, push(), , , pop(), . private : m_mutex
. , QStack<T> . QStack<T> , -
, . push()
lock() , ,
unlock() . ,
.
pop() QMutexLocker.
. . , . ,
, push(),
, .

: , ,
. , ,
. , , , .
,
, . ,
:
. Qt
.

. , , . . ,

538

VI. Qt

, . ,
, ,
. . . , ,
. ,
, .
. QSemaphore.
.
QMutex, lock() unlock() acquire() release() :
QSemaphore sem(1);
sem.acquire();

. acquire() , .
, .
.
acquire(), , ,
, .
acquire(),
.
release() .
.
"" tryAcquire()
.


Qt QWaitCondition, . , .
, QWaitCondition::wait() . , , , QWaitCondition::wakeOne() QWaitCondition::wakeAll().
, ,
. , . wait() , .


, , . ,
"A", "B". "B"
"A". , , ,
. , , . .

39.

539

, "" .
(deadlock) (. 39.6).
. , ,
, ,
, .

. 39.6.

QtConcurrent
,
, , "
", .
Qt QtConcurrent.
, . , .
, ,
QtConcurrent::run(). 39.11.
39.11. main.cpp. QtConcurrent

// ---------------------------------------------------------------------QString myToUpper(const QString& str)


{
return str.toUpper();
}

VI. Qt

540

// ---------------------------------------------------------------------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() ;
QFuture::isStarted() ;
QFuture::isPaused() QFuture::pause().

, ,
myToUpper().
QtConcurrent::mapped().
, myToUpper() . main() 39.11.
39.12. main.cpp. QtConcurrent

int main(int argc, char** argv)


{
QCoreApplication app(argc, argv);
QStringList lst(QStringList() << "one" << "two" << "three");
QFuture<QString> future = QtConcurrent::mapped(lst, myToUpper);
future.waitForFinished();
qDebug() << future.results();
return 0;
}

39.

541

39.12
QtConcurrent::mapped() . ,
myToUpper(). ,
, QFuture::waitForFinished()

. :
"ONE", "TWO", "THREE"

,
. , .
. .

, .
, , . ,
.
QThread
run(), .
, start().
, exec() run().

.
.
. Qt QMutex,
QWaitContion QSemaphore.
Qt
.
QtConcurrent .

40


, .
. ""


( . socket , )
. ,
, , .
- (point to point), .
(datagram) (stream). . .
, , - , .
, , , , , .
Qt QUdpSocket,
QTcpSocket.
QTcpSocket TCP (Transmition Control Protocol,
) ,
. . , HTTP, FTP, POP3, SMTP, . QAbstractSocket, , ,
QIODevice. , ( )
QIODevice QDataStream
QTextStream (. 37).
QTcpSocket , . ,
, waitFor. -

40.

543

, , .
.
QUdpSocket UDP (User Datagram Protocol, ). ,
. ,
, . . ,
. , TCP,
.
UDP .
,
. , ,
, ,
, , , . UDP , . , , .
TCP
UDP. , .
: TCP, UDP.

"-"
"-" : , (. 40.1). , ,
, . ,
IP- ,
. , , , . ,
. ,
, . , .

. 40.1. "-"

VI. Qt

544

.
(. 40.1).
40.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

HTTP-

TCP-
Qt QTcpServer,
TCP-. ,
. 40.2, , .

. 40.2.

40.

545

40.1. main.cpp

#include <QtGui>
#include "MyServer.h"
int main(int argc, char** argv)
{
QApplication app(argc, argv);
MyServer
server(2323);
server.show();
return app.exec();
}

40.1 . , 40.240.6 MyServer,


, .
, 2323.
40.2. MyServer.h

#ifndef _MyServer_h_
#define _MyServer_h_
#include <QWidget>
class QTcpServer;
class QTextEdit;
class QTcpSocket;
// ======================================================================
class MyServer : public QWidget {
Q_OBJECT
private:
QTcpServer* m_ptcpServer;
QTextEdit* m_ptxt;
quint16
m_nNextBlockSize;
private:
void sendToClient(QTcpSocket* pSocket, const QString& str);
public:
MyServer(int nPort, QWidget* pwgt = 0);
public slots:
virtual void slotNewConnection();
void slotReadClient
();
};
#endif //_MyServer_h_

VI. Qt

546

MyServer, 40.2, m_ptcpServer, . m_nNextBlockSize


.
m_ptxt .
40.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("<H1>Server</H1>"));
pvbxLayout->addWidget(m_ptxt);
setLayout(pvbxLayout);
}

listen() ( 40.3).
, . , , false, .
, ( 40.4)
slotNewConnection() newConnection(), .
( m_ptxt) , , setReadOnly().
40.4. MyServer.pp. slotNewConnection()

/*virtual*/ void MyServer::slotNewConnection()


{
QTcpSocket* pClientSocket = m_ptcpServer->nextPendingConnection();

40.
connect(pClientSocket,
pClientSocket,
);
connect(pClientSocket,
this,
);

547

SIGNAL(disconnected()),
SLOT(deleteLater())
SIGNAL(readyRead()),
SLOT(slotReadClient())

sendToClient(pClientSocket, "Server Response: Connected!");


}

slotNewConnection(), 40.4, . nextPendingConnection(), ,


. - . disconnected(),
, QObject::deleteLater(), .
readyToRead(), slotReadClient().
40.5. MyServer.cpp. slotReadClient()

void MyServer::slotReadClient()
{
QTcpSocket* pClientSocket = (QTcpSocket*)sender();
QDataStream in(pClientSocket);
in.setVersion(QDataStream::Qt_4_5);
for (;;) {
if (!m_nNextBlockSize) {
if (pClientSocket->bytesAvailable() < sizeof(quint16)) {
break;
}
in >> m_nNextBlockSize;
}
if (pClientSocket->bytesAvailable() < m_nNextBlockSize) {
break;
}
QTime
time;
QString str;
in >> time >> str;
QString strMessage =
time.toString() + " " + "Client has sent " + str;
m_ptxt->append(strMessage);
m_nNextBlockSize = 0;
sendToClient(pClientSocket,
"Server Response: Received \"" + str + "\""
);
}
}

VI. Qt

548

40.5 ,
sender(), QTcpSocket. for ,
. ""
, , .
. ,
m_nNextBlockSize
(. . ). , time str.
time toString()
str strMessage,
append(). m_nNextBlockSize 0, ,
. sendToClient() ,
.
40.6. MyServer.cpp. sendToClient()

void MyServer::sendToClient(QTcpSocket* pSocket, const QString& str)


{
QByteArray arrBlock;
QDataStream out(&arrBlock, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_5);
out << quint16(0) << QTime::currentTime() << str;
out.device()->seek(0);
out << quint16(arrBlock.size() sizeof(quint16));
pSocket->write(arrBlock);
}

sendToClient() , ( 40.6). , , , , , . .
. .
arrBlock QByteArray.
QDataStream, ,
0. seek(),
arrBlock, sizeof(quint16), (out) , .
write().

QTextStream.
QDataStream,
. , QTime. QDataStream,
, , . .

40.

549

TCP-
QTcpSocket,
connectToHost(), ( IP-),
. QTcpSocket
, , connected(). error(int) , QAbstractSocket::
SocketError. , , ,
.
QTcpSocket .
40.3 . , ,
Send ().

. 40.3.

40.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();
}

main(), 40.7,
(. 40.840.13). ,
"localhost". 2323, . . , .

VI. Qt

550
40.8. MyClient.h

#ifndef _MyClient_h_
#define _MyClient_h_
#include <QWidget>
#include <QTcpSocket>
class QTextEdit;
class QLineEdit;
// ======================================================================
class MyClient : public QWidget {
Q_OBJECT
private:
QTcpSocket* m_pTcpSocket;
QTextEdit* m_ptxtInfo;
QLineEdit* m_ptxtInput;
quint16
m_nNextBlockSize;
public:
MyClient(const QString& strHost, int nPort, QWidget* pwgt = 0) ;
private slots:
void slotReadyRead
(
);
void slotError
(QAbstractSocket::SocketError);
void slotSendToServer(
);
void slotConnected
(
);
};
#endif //_MyClient_h_

MyClient, 40.8, m_pTcpSocket, , m_nNextBlockSize,


. , m_txtInfo m_txtInput, .
40.9. MyClient.cpp. MyClient

MyClient::MyClient(const QString& 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()));

40.

551

connect(m_pTcpSocket, SIGNAL(readyRead()), SLOT(slotReadyRead()));


connect(m_pTcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
this,
SLOT(slotError(QAbstractSocket::SocketError))
);
m_ptxtInfo = new QTextEdit;
m_ptxtInput = new QLineEdit;
m_ptxtInfo->setReadOnly(true);
QPushButton* pcmd = new QPushButton("&Send");
connect(pcmd, SIGNAL(clicked()), SLOT(slotSendToServer()));
connect(m_ptxtInput, SIGNAL(returnPressed()),
this,
SLOT(slotSendToServer())
);
//Layout setup
QVBoxLayout* pvbxLayout = new QVBoxLayout;
pvbxLayout->addWidget(new QLabel("<H1>Client</H1>"));
pvbxLayout->addWidget(m_ptxtInfo);
pvbxLayout->addWidget(m_ptxtInput);
pvbxLayout->addWidget(pcmd);
setLayout(pvbxLayout);
}

40.9 ,
( m_pTcpSocket). connectToHost() , . ,
. .
connected(), , readyRead() .
slotConnected() slotReadyRead(). error(), slotError(), .
, , ,
. clicked() slotSendToServer() MyClient, .
<Enter>, returnPressed()
(m_ptxtInput) slotSendToServer().
40.10. MyClient.cpp. slotReadyRead()

void MyClient::slotReadyRead()
{
QDataStream in(m_pTcpSocket);
in.setVersion(QDataStream::Qt_4_5);
for (;;) {
if (!m_nNextBlockSize) {

VI. Qt

552

if (m_pTcpSocket->bytesAvailable() < sizeof(quint16)) {


break;
}
in >> m_nNextBlockSize;
}
if (m_pTcpSocket->bytesAvailable() < m_nNextBlockSize) {
break;
}
QTime
time;
QString str;
in >> time >> str;
m_ptxtInfo->append(time.toString() + " " + str);
m_nNextBlockSize = 0;
}
}

40.10 slotReadyToRead(),
. for ,
. , ,
, .
.
, ,
>> QDataStream ( in). . ( m_ptxtInfo) append().
m_nNextBlockSize 0,
, .
40.11. MyClient.cpp. slotError()

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);
}

slotError(), 40.11, .
, .

40.

553

40.12. MyClient.cpp. slotSentToServer()

void MyClient::slotSendToServer()
{
QByteArray arrBlock;
QDataStream out(&arrBlock, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_5);
out << quint16(0) << QTime::currentTime() << m_ptxtInput->text();
out.device()->seek(0);
out << quint16(arrBlock.size() sizeof(quint16));
m_pTcpSocket->write(arrBlock);
m_ptxtInput->setText("");
}

40.12 .
, (. 40.6),
. MyServer::sendToClient() ,
,
setText() ( clear()).
,

slotSendToServer() Send () <Enter>


( m_ptxtInput()).
40.13. MyClient.cpp. slotConnected()

void MyClient::slotConnected()
{
m_ptxtInfo->append("Received the connected() signal");
}

, slotConnected().
( 40.13).

UDP- UDP-
UDP- QUdpSocket.
writeDatagram().
, QUdpSocket,
bind(). , , readyRead().
readDatagram().
, , . ,
.

VI. Qt

554

UDP- UDP- , . 40.4. ,


.

. 40.4. UDP- UDP-

40.14. UdpServer.h

class UdpServer : public QTextEdit {


Q_OBJECT
private:
QUdpSocket* m_pudp;
public:
UdpServer(QWidget* pwgt = 0);
private slots:
void slotSendDatagram();
};

. UdpServer
QUdpSocket ( 40.14), m_pudp.
slotSendDatagram().
40.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);
ptimer->start();
connect(ptimer, SIGNAL(timeout()), SLOT(slotSendDatagram()));
}

40.

555


UdpServer ( 40.15), setWindowTitle()
QUdpSocket. , ,
0,5 , start() slotSenDatagram().
40.16. UdpServer.cpp. slotSendDatagram()

void UdpServer::slotSendDatagram()
{
QByteArray baDatagram;
QDataStream out(&baDatagram, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_7);
QDateTime dt = QDateTime::currentDateTime();
append("Sent:" + dt.toString());
out << dt;
m_pudp->writeDatagram(baDatagram, QHostAddress::LocalHost, 2424);
}

40.16 slotSendDatagram(),
. . QDataStream baDatagram.
writeDatagram(),
baDatagram, IP-
. IP-,
QHostAddress::LocalHost, 127.0.0.1.

QAbstractSoket QUdpSocket IP-. IP-
, fromName()
QHostName.

.
40.17. UdpClient.h

class UdpClient : public QTextEdit {


Q_OBJECT
private:
QUdpSocket* m_pudp;
public:
UdpClient(QWidget* pwgt = 0);
private slots:
void slotProcessDatagrams();
};

VI. Qt

556

UDP- ( 40.17). ,
QUdpSocket, m_pudp. slotProcessDatagrams(), .
40.18. UdpClient.cpp.

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()));
}

, "UdpClient" ( 40.18). QUdpSocket


bind() 2424.
IP- , .
readyRead() slotProcessDatagrams().
40.19. UdpClient.cpp. 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(&baDatagram, QIODevice::ReadOnly);
in.setVersion(QDataStream::Qt_4_7);
in >> dateTime;
append("Received:" + dateTime.toString());
}

40.19 QUdpSocket
. ,
,
. do...while(), . . , ,
.
pendingDatagramSize() .
, ,

40.

557

. , ,
. readDatagram()
baDatagram. in
, , .
QTextEdit::append().


Qt QFtp QHttp, QObject. ,
.
, , , ,
setProgress() .
done().

QFtp
. FTP
(File Transfer Protocol, ) , .
. , c
. , :
get ;
put ;
rmdir ;
mkdir ;
cd ;
rename ;
close .

QFtp FTP-
FTP. , .
FTP-: get()
get, put() put . .
get() QIODevice,
, ,
readRead(), QFtp::read() QFtp::readAll().

QFtp::cd() , , QFtp::list().

VI. Qt

558

listInfo()
QUrlInfo. , , QFileInfo.

, QFtp FTP-.
rawCommand() , , :
ftp.rawCommand("MKDIR MyDir");

, QFtp.
. , QFtp
commandStarted(int),
commandFinished(int, bool).
int.
QFtp FTP-:
connectToHost() login(). 40.20 index.txt, , FTP
index.txt. , FTP-,
QFtp::connectToHost() 21 , ( , ).
get(), -.
40.20. FTP-

QFile file("index.txt");
QFtp ftp;
if (file.open(QIODevice::WriteOnly)) {
ftp.connectToHost("ftp.microsoft.com");
ftp.login();
ftp.cd("Softlib");
ftp.get("index.txt", &file);
...
}

,
done(bool).

QHttp
HTTP (HyperText Transfer Protocol, )
. ,
FTP. ,
FTP : , .
Qt QHttp HTTP. QFtp. 40.21

40.

559

, www.neonway.com/wallpaper/
images/, image.jpg.
40.21. HTTP-

QFile file("image.jpg");
QHttp http;
if (file.open(QIODevice::WriteOnly)) {
http.setHost("www.neonway.com");
http.get("/wallpaper/images/traderstar.jpg", &file);
...
}

,
, done(bool).

Qt4.6 QHttp ,
, , .
" ", HTTP
FTP. .
.


, QHttp QFtp,
, .
,
. ,
(cookie), (proxy), , .
: QNetworkAccessManager, QNetworkRequest
QNetworkReply.
QNetworkAccessManager . , :
head ;
get ;
put ;
post get put HTTP.

. .
QNetworkRequest , ,
URL. , , , HTTP- .
QNetworkReply , URL, HTTP-
, . . :

VI. Qt

560
readyRead() ;
finished() ;
error() ;

downloadProgress() uploadProgress() .

QNetworkRequest QNetworkReplay :
QNetworkRequest , QNetworkReply
.
, HTTP, (. 40.5), .

. 40.5.

40.22. main.cpp.

#include <QApplication>
#include "DownloaderGui.h"
int main(int argc, char** argv)
{
QApplication app(argc, argv);
DownloaderGui downloader;
downloader.show();
return app.exec();
}

( 40.22)
DownloaderGui show().

40.

561

40.23. Downloader.h

#ifndef _Downloader_h_
#define _Downloader_h_
#include <QObject>
#include <QUrl>
class QNetworkAccessManager;
class QNetworkReply;
// ======================================================================
class Downloader : public QObject {
Q_OBJECT
private:
QNetworkAccessManager* m_pnam;
public:
Downloader(QObject* pobj = 0);
void download(const QUrl&);
signals:
void downloadProgress(qint64, qint64
);
void done
(const QUrl&, const QByteArray&);
void error
(
);
private slots:
void slotFinished(QNetworkReply*);
};
#endif //_Downloader_h_

, 40.23, QObject QNeworkAccessManager,


. download()
QUrl. , downloadProgress(), done() error(). slotFinished()
done() error().
40.24. Downloader.cpp.

Downloader::Downloader(QObject* pobj/*=0*/) : QObject(pobj)


{
m_pnam = new QNetworkAccessManager(this);
connect(m_pnam, SIGNAL(finished(QNetworkReply*)),
this,
SLOT(slotFinished(QNetworkReply*))
);
}

562

VI. Qt

40.24 QNetworkAccessManager finished() slotFinished().


QNetworkReply, .
40.25. Downloader.cpp. download()

void Downloader::download(const QUrl& url)


{
QNetworkRequest request(url);
QNetworkReply* pnr = m_pnam->get(request);
connect(pnr, SIGNAL(downloadProgress(qint64, qint64)),
this, SIGNAL(downloadProgress(qint64, qint64))
);
}

download(), 40.25,
QNetworkRequest,
QNetworkAccessManager. get() .
, . . , QNetworkReply, ,
, downloadProgress().
40.26. Downloader.cpp. slotFinished()

void Downloader::slotFinished(QNetworkReply* pnr)


{
if (pnr->error() != QNetworkReply::NoError) {
emit error();
}
else {
emit done(pnr->url(), pnr->readAll());
}
pnr->deleteLater();
}

slotFinished() ( 40.26).
, , error(), QNetworkReply::NoError, . . , error(). , . .
, done(). URL . QNetworkReply
readAll().
QNetworkReply, . . , . deleteLater(),
, delete C++, . .
, -

40.

563

. ,
.
40.27. DownloaderGui.h

#ifndef _DownloaderGui_h_
#define _DownloaderGui_h_
#include <QWidget>
#include <QUrl>
class
class
class
class

Downloader;
QProgressBar;
QLineEdit;
QPushButton;

// ======================================================================
class DownloaderGui : public QWidget {
Q_OBJECT
private:
Downloader*
QProgressBar*
QLineEdit*
QPushButton*

m_pdl;
m_ppb;
m_ptxt;
m_pcmd;

void showPic(const QString&);


public:
DownloaderGui(QWidget* pwgt = 0);
private slots:
void slotGo
(
);
void slotError
(
);
void slotDownloadProgress(qint64, qint64
);
void slotDone
(const QUrl&, const QByteArray&);
};
#endif //_DownloaderGui_h_

, . 40.5 40.27,
( m_ppb),
( m_ptxt) ( m_pcmd). , "" Downloader ( m_dl).
showPic()
. :
slotGo() ;
slotError() ;
slotDownloadProgress() ,

;
slotDone() .

VI. Qt

564
40.28. DownloaderGui.cpp.

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&))
);
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);
}

, 40.28,
, Downloader. setText() strDownloadLink,
.
slotGo(), downladProgress() Downloader slotDownloadProgress()
slotDone(). QGridLayout.
40.29. DownloaderGui.cpp. slotGo()

void DownloaderGui::slotGo()
{
m_pdl->download(QUrl(m_ptxt->text()));
}

40.29 . ,
( text()), . . ,
download(), .

40.

565

40.30. DownloaderGui.cpp. slotDownloadProgress()

void DownloaderGui::slotDownloadProgress(qint64 nReceived, qint64 nTotal)


{
if (nTotal <= 0) {
slotError();
return;
}
m_ppb->setValue(100 * nReceived / nTotal);
}

40.30 , , nTotal,
. , . ,
, , ,
. slotError(),
, . ,
setValue()
.
40.31. DownloaderGui.cpp. slotDone()

void DownloaderGui::slotDone(const QUrl& url, const QByteArray& ba)


{
QFile file(url.path().section('/', -1));
if (file.open(QIODevice::WriteOnly)) {
file.write(ba);
file.close();
if (strFileName.endsWith(".jpg")
|| strFileName.endsWith(".png")
) {
showPic(strFileName);
}
}
}

slotDone() ( 40.31).
, , (link), (
url), ( ba). .
,
. ,
JPG PNG, ,
showPic(), .

566

VI. Qt

40.32. DownloaderGui.cpp. showPic()

void DownloaderGui::showPic(const QString& 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();
}

( 40.32) , 3
scaled() Qt::SmoothTransforamtion. setPixmap() QLabel setFixedSize(). show().
40.33. DownloaderGui.cpp. slotError()

void DownloaderGui::slotError()
{
QMessageBox::critical(0,
tr("Error"),
tr("An error while download is occured")
);
}

, 40.33,
.


, , , , . . . , ,
.
, waitFor...().
QAbstractSocket , :
waitForConnected() ;
waitForReadyRead() ;

40.

567

waitForBytesWritten() , ;
waitForDisconnected() ;
waitForEncrypted() ( QSslSocket).

, .
30 .
TCP- ,
40.34.
40.34. TCP-

int main(int argc, char** argv)


{
QCoreApplication app(argc, argv);
QTcpServer
tcpServer;
int
nPort = 2424;
if (!tcpServer.listen(QHostAddress::Any, nPort)) {
qDebug() << "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 hh:mm:ss");
pSocket->write(strDateTime.toLatin1());
qDebug() << "Server date & time:" + strDateTime;
pSocket->disconnectFromHost();
if (pSocket->state() == QAbstractSocket::ConnectedState){
pSocket->waitForDisconnected();
}
delete pSocket;
} while (tcpServer.hasPendingConnections());
}
}
return 0;
}

40.34 , , .
QTcpServer , "" ,
2424.

VI. Qt

568

!
Mac OS X , 80 (HTTP), . sudo.

forever while
, ,
, .

nextPendingConnection(), pSocket.
strDateTime, write() . , ,
disconnectFromHost() , ,
waitForDisconnected().
waitForDisconnected() , :
QAbstractSocket::waitForDisconnected() is not allowed in UnconnectedState

, ,
QAbstractSocket::ConnectedState, . . , waitForDisconnected() . delete .
, , ,
, . , , ,
forever.
40.35. TCP-

#include <QtCore>
#include <QtNetwork>
int main(int argc, char** argv)
{
QCoreApplication app(argc, argv);
QTcpSocket
socket;
socket.connectToHost(QHostAddress::LocalHost, 2424);
socket.waitForDisconnected();
qDebug() << socket.readAll();
return 0;
}

TCP-, 40.35, .
(socket) connectToHost() . QHostAddress::LocalHost ,
, . -

40.

569

, .
waitForDisconnected() , .
.
, : QHttp, QFtp QNetworkAccessManager, waitFor...().
, .
40.25 ,
download() ,
, .
void Downloader::download(const QUrl& url)
{
QNetworkRequest request(url);
QNetworkReply* pnr = m_pnam->get(request);
QEventLoop
loop;
connect(&request, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
}


, ,
, -, , ,
, , ,
- . - QNetworkProxy. 40.36.
40.36. -

QNetworkProxy proxy;
proxy.setType(QNetworkProxy::HttpProxy);
proxy.setHostName("192.168.178.1");
proxy.setPort(8080);
proxy.setUser("user");
proxy.setPassword("password");
QNetworkProxy::setApplicationProxy(proxy);

40.36 QNetworkProxy , IP-,


, -.
setApplicationProxy() .

TCP UDP. , , -

570

VI. Qt

. , UDP
, , TCP.

. : .
"-" :
, ,
. ,
. .
Qt QFtp QHttp, , QNetworkAccessManager.

41

XML

, - ,
,
.

XML(Extensible Markup Language, ) . , , , XML.


, . XML.
XML 1996 ., 1998 . W3C (World Wide Web
Consortium) . , XML SGML,
80-. XML , HTML,
, SGML, , ,
, .
XML , . XML
, XML. XML-
ASCII Unicode, . XML , , Notepad () Windows.


XML-
XML .
: , ,
. . XML HTML. XML
. , XML
, HTML, , XML ,
XML-, .

.

572

VI. Qt

, XML-,
, ,
, :
<?xml version = "1.0"?>
<!-- My 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 631322181</phone>
<email>kermit@mega.de</email>
</contact>
</addressbook>

XML- , . XML-
(elements). < >, . . ,
<name>, , </name>.
, <name>Piggy</name>, . , , <empty></empty>.
XML ,
<empty/>. ,
, , , , <empty number = "1"></empty>
<empty number = "1"/>. , .
XML- ,
, <!-- -->.
HTML XML :
,

, . , XML <p> , HTML, , ,


properties ();
-

. , , ,
, <Tag></Tag> <tag></tag> .
. 41.1 . ,
XML- .

41. XML

573

. 41.1. XML-

XML Qt
Qt XML. , Qt Designer
(. 45) .
Qt, (. 31).
XML Qt QtXml, . :
:
QT += xml

,
QtXml.
#include <QtXml>

Qt XML. DOM, SAX, QXmlStreamReader. ,


, .

DOM
DOM (Document Object Model, ) API
XML-, W3C. Qt , W3C
(name spaces). C DOM XML- .
. , , , DOM .

VI. Qt

574
. 41.2.
DOM

. 41.2 QDomNode,
Qt DOM.
DOM
QtXml.
QDomNode, QDomElement,
QDomAttr QDomText.

XML-
QDomElement . DOM
. , . ,
, ,
QDomElement.
DOM QDomNode,
.
, , ,
. QDomNode QDomElement QDomNode::toElement().
, ,
isNull().
, 41.141.3, XML-
:
Attr: "1"
TagName: "name"
TagName: "phone"
TagName: "email"
Attr: "2"
TagName: "name"
TagName: "phone"
TagName: "email"

Text:
Text:
Text:

"Piggy"
"+49 631322187"
"piggy@mega.de"

Text:
Text:
Text:

"Kermit"
"+49 631322181"
"kermit@mega.de"

41.1. XmlDOMRead.pro

TEMPLATE
= app
QT
+= xml
win32: CONFIG += console
SOURCES
= main.cpp
TARGET
= ../XmlDOMRead

41. XML

575

XML Qt ,
QT pro- ( 41.1). CONFIG,
console. ,
OC Windows.
41.2. main.cpp

#include <QtXml>
// ---------------------------------------------------------------------void traverseNode(const QDomNode& node)
{
QDomNode domNode = node.firstChild();
while(!domNode.isNull()) {
if(domNode.isElement()) {
QDomElement domElement = domNode.toElement();
if(!domElement.isNull()) {
if(domElement.tagName() == "contact") {
qDebug() << "Attr: "
<< domElement.attribute("number", "");
}
else {
qDebug() << "TagName: " << domElement.tagName()
<< "\tText: " << domElement.text();
}
}
}
traverseNode(domNode);
domNode = domNode.nextSibling();
}
}
// ---------------------------------------------------------------------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;
}

main(), 41.2, QDomDocument


QFile. QDomDocument XML-.

VI. Qt

576

XML- setContext() QDomDocument


, , QIODevice.
QFile. , QDomElement
documentElement() QDomDocument,
XML-. traverseNode(), XML-.
DOM .
traverseNode() firstChild() nextSibling() QDomNode.
nextSibling() , ,
. isElement(). , QDomElement toElement() QDomElement.
( tagName()) "contact" attribute() number.
tagName() text() .

XML-
XML-
. QDomDocument ,
createElement(), createTextNode(), createAttribute(). . , 41.3,
XML-.
41.3. main.cpp. main()

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");
domElement.appendChild(contact1);
domElement.appendChild(contact2);
domElement.appendChild(contact3);
QFile file("addressbook.xml");
if(file.open(QIODevice::WriteOnly)) {
QTextStream(&file) << doc.toString();

41. XML

577

file.close();
}
return 0;
}

QDomDocument , ( 41.3).
"addressbook". appendChild() . contact() , ( 41.4). appendChild()
domElement. XML-
toString(), XML-,
.
41.4. main.cpp. contact()

QDomElement contact(
QDomDocument&
const QString&
const QString&
const QString&
)
{
static int nNumber = 1;

domDoc,
strName,
strPhone,
strEmail

QDomElement domElement = makeElement(domDoc,


"contact",
QString().setNum(nNumber)
);
domElement.appendChild(makeElement(domDoc, "name", "", strName));
domElement.appendChild(makeElement(domDoc, "phone", "", strPhone));
domElement.appendChild(makeElement(domDoc, "email", "", strEmail));
nNumber++;
return domElement;
}

41.4 contact(). ,
. .
makeElement(), , .
41.5. main.cpp. makeElement()

QDomElement makeElement(
const
const
const
)

QDomDocument&
QString&
QString&
QString&

domDoc,
strName,
strAttr = QString(),
strText = QString()

VI. Qt

578
{

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;
}

41.5 makeElement(),
createElement() QDomDocument. , number. createAttribute() QDomDocument.
setValue() . , createTextNode()
QDomNode . appendChild() .

SAX
, DOM . XML-
SAX.
SAX (Simple API for XML, API XML) Java API XML-. SAX XML, .

XML-
QXmlSimpleReader XML-, SAX.
XML- , , . :
, XML-. , . . , XML-.
SAX . 41.3. QXmlContentHandler QXmlSimpleReader. ,
QXmlEntityResolver, QXmlDTDHandler, QXmlErrorHandler, QXmlDeclHandler
QxmlLexicalHandler, ,
XML-.

41. XML

579

. 41.3.
SAX

, XML-
: QXmlContentHandler QXmlErrorHandler. QXmlContentHandler
, .
:
1. startDocument() XML-.
2. startElement() .
3. characters() .
4. endElement() .
5. endDocument() .
QXmlDefaultHandler,
(. . 41.3). .
XML- :
startDocument(),
startElement(),
characters(),
endElement(),
endDocument()

fatalError(). QXmlErrorHandler.
true,
QXmlSimpleReader , . false
, , errorString().
, 41.6 41.7, XML-.
, 41.1 41.2.
41.6. main.cpp. main()

int main()
{
AddressBookParser
QFile
QXmlInputSource
QXmlSimpleReader

handler;
file("addressbook.xml");
source(&file);
reader;

reader.setContentHandler(&handler);
reader.parse(source);
return 0;
}

VI. Qt

580

, 41.6,
AddressBookParser (. 41.7), QFile ( ) QXmlSimpleReader (
). XML- SAX-,
QXmlInputSource, QIODevice. parse() QXmlSimpleReader. XML-. setContentHandler()
, QXmlContentHandler,
XML-.
41.7. main.cpp. AddressBookParser

class AddressBookParser : public QXmlDefaultHandler {


private:
QString m_strText;
public:
// -----------------------------------------------------------------bool startElement(const QString&,
const QString&,
const QString&,
const QXmlAttributes& attrs
)
{
for(int i = 0; i < attrs.count(); i++) {
if(attrs.localName(i) == "number") {
qDebug() << "Attr:" << attrs.value(i);
}
}
return true;
}
// -----------------------------------------------------------------bool characters(const QString& strText)
{
m_strText = strText;
return true;
}
// -----------------------------------------------------------------bool endElement(const QString&, const QString&, const QString& str)
{
if (str != "contact" && str != "addressbook") {
qDebug() << "TagName:" << str
<< "\tText:" << m_strText;
}
return true;
}

41. XML

581

// -----------------------------------------------------------------bool fatalError(const QXmlParseException& exception)


{
qDebug() << "Line:"
<< exception.lineNumber()
<< ", Column:" << exception.columnNumber()
<< ", Message:" << exception.message();
return false;
}
};

41.7 AddressBookParser , XML-. startElement() endElement(), , . startElement()


, . , , XML, , , , ,
.
number, . characters()
m_strText. ,
AddressBookParser.
endElement() , . , , . contact
addressbook, . fatalError()
, XML-.
XML-, , .

QXmlStreamReader XML
Qt XML-
QXmlStreamReader. SAX,
, . . , SAX. , SAX.
QXmlStreamReader 41.8.
41.8. main.cpp. QXmlStreamReader

#include <QtXml>
int main()
{
QFile file("addressbook.xml");
if(file.open(QIODevice::ReadOnly)) {
QXmlStreamReader sr(&file);
do {
sr.readNext();
qDebug() << sr.tokenString() << sr.name() << sr.text();
} while(!sr.atEnd());

VI. Qt

582

if (sr.hasError()) {
qDebug() << "Error:" << sr.errorString();
}
file.close();
}
return 0;
}

41.8 XML- addressbook.xml .


QXmlStreamReader sr. readNext(), do...while(), , .
( tokenString()), ( name())
( text()). ,
( atEnd()).
hasError() ( errorString()).
:
"StartDocument" "" ""
"Comment" "" " My Address Book "
"StartElement" "addressbook" ""
"Characters" "" ""
"StartElement" "contact" ""
"Characters" "" ""
"StartElement" "name" ""
"Characters" "" "Piggy"
"EndElement" "name" ""
"Characters" "" ""
"StartElement" "phone" ""
"Characters" "" "+49 631322187"
"EndElement" "phone" ""
"Characters" "" ""
"StartElement" "email" ""
"Characters" "" "piggy@mega.de"
"EndElement" "email" ""
"Characters" "" ""
"EndElement" "contact" ""
"Characters" "" ""
"StartElement" "contact" ""
"Characters" "" ""
"StartElement" "name" ""
"Characters" "" "Kermit"
"EndElement" "name" ""
"Characters" "" ""
"StartElement" "phone" ""
"Characters" "" "+49 631322181"
"EndElement" "phone" ""

41. XML

583

"Characters" "" ""


"StartElement" "email" ""
"Characters" "" "kermit@mega.de"
"EndElement" "email" ""
"Characters" "" ""
"EndElement" "contact" ""
"Characters" "" ""
"EndElement" "addressbook" ""
"EndDocument" "" ""

XQuery
XQuery (XML Query Language, XML). ,
XML- . , XSLT, SQL C. Qt
XQuery QXmlQuery,
QtXmlPatterns. XQuery . pro-.
QtXmlPatterns : QT += xmlpatterns.
41.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]);
if(xqFile.open(QIODevice::ReadOnly)) {
strQuery = xqFile.readAll();
xqFile.close();
}
else {
qDebug() << "Can't open the file for reading:" << argv[1];
return 0;
}
QFile xmlFile(argv[1]);
if(xmlFile.open(QIODevice::ReadOnly)) {
QXmlQuery query;
query.bindVariable("inputDocument", &xmlFile);
query.setQuery(strQuery);

VI. Qt

584
if (!query.isValid()) {
qDebug() << "The query is invalid";
return 0;
}
QString strOutput;
if (!query.evaluateTo(&strOutput)) {
qDebug() << "Can't evaluate the query";
return 0;
}
xmlFile.close();
qDebug() << strOutput;
}
return app.exec();
}

41.9 , : , XML-, XQ- c XQuery .


.
strQuery XQ-,
( 2). XML- ( xmlFile)
, , QXmlQuery. XQuery- XML-,
inputDocument QXmlQuery::bindVariable().
QXmlQuery::setQuery() , XQ-, QXmlQuery::isValid() .
QXmlQuery::evaluateTo()
QString, .
,
qDebug().
41.10. _all.xq.

declare variable $inputDocument external;


doc($inputDocument)/addressbook/contact/
concat('(name:', name, ' email:', email, ' phone:', phone, ') ')

, 41.10, XML-.
XML- declare
variable. external , , .
"/addressbook/contact/"
concat() . :
XQuery addressbook.xml _all.xq

41. XML

585

:
(name:Piggy email:piggy@mega.de phone:+49 631322187)
(name:Kermit email:kermit@mega.de phone:+49 631322181)
41.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)

, 41.11,
for, where, order by return. SELECT FROM WHERE SQL.
41.11 for x,
, "/addressbook/contact/name". where
,
, "Kermit". order by ( ,
. . ). return , .
:
XQuery addressbook.xml _kermit.xq

:
"Kermit".
41.12. _piggy.xq.

declare variable $inputDocument external;


doc($inputDocument)/addressbook/contact[xs:integer(@number) = 1]/
concat(name, '; ', email, '; ', phone)

41.2 , .
, number 1. concat(). :
XQuery addressbook.xml _piggy.xq

:
"Piggy; piggy@mega.de; +49 631322187"


XML- , ,
, :
doc($inputDocument)/addressbook/contact[xs:integer(@number) < 20 and @land = "
Germany"]/.

VI. Qt

586

,
20 .


. "addressbook" , . :
doc($inputDocument)/addressbook[@owner = "Max Schlee"]/contact/.
,
Max Schlee.
41.13. _ount.xq.

declare variable $inputDocument external;


count(doc($inputDocument)//contact)

, , :
empty() true, , count(), . 41.13 count() , XML-. :
XQuery addressbook.xml _count.xq

:
"2"

XML. XML
.
Qt XML-: DOM, SAX
QXmlStreamReader. XML- ( ), .
XML- .
, .
, SAX , . ,
. ,
XML-, . . SAX .
XQuery Qt QtXmlPatterns. XML-, . SQL . QtXmlPatterns.

42


,
, ... .

, .
, . (. 42.1). , / . , , , .
,
, .

. 42.1. ()

: , , . .
SQL (Structured Query Language, ), ,
.

SQL
, , : , ( ), , .
, SQL, . -

588

VI. Qt

SQL ,
, ( ), . , ,
.
, SQL , . . ,
, . , "SELECT", "select", "Select" . .
SQL . , SQL
.


, . 42.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, 'Kermit', '+49 631322181', 'kermit@mega.de');


SELECT ... FROM ... WHERE . , .
, .
:
1. SELECT , . .
, . SELECT *, , .
.
2. FROM , .

42.

589

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>

:
1. .
2. .
3. .

VI. Qt

590

.
, QSqlDriver, QSqlDriverCreator<T*>, QSqlDriverCreatorBase,
QSqlDriverPlugin QSqlResult.
. : QSqlDatabase, QSqlQuery,
QSqlError, QSqlField, QSqlIndex QSqlRecord.
. : QSqlQueryModel, QSqlTableModel
QSqlRelationalTableModel.
,
. , Qt. , Qt . 42.1. , ( SQLite), "-",
. , SQLite, ,
Qt.
42.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

, .
Qt ,
(plug-ins).
. Qt
,
,
configure I

42.

591

L . plugin-sql-
: db2, ibase, mysql, oci, odbc, psql, sqlite, sqlite2 tbs. ,
MySQL 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


, QtSql,
plugin-sql- qt-sql-.

, . Qt (src),
plugins/sqldrivers. . , PostgreSQL psql.
, Windows:
qmake "INCLUDEPATH+=C:/psql/include LIBS+=C:/psql/libpq.a"

Linux:
qmake "INCLUDEPATH+=/usr/include/pgsql LIBS+=-LC:/usr/lib lpg"


MinGW, reimp. , Windows *.lib,
Microsoft. MSYS MinGW.

!
, ,
. , Windows
<MyApplication>/sqldrivers/. Linux
, Mac OS X macdeployqt, . , . ,
, .

( )
.
QSqlDatabase::addDatabase() ( 42.1).
, (. . 42.1).
42.1. main.cpp.

static bool createConnection()


{
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("addressbook");

VI. Qt

592

db.setUserName("elton");
db.setHostName("epica");
db.setPassword("password");
if (!db.open()) {
qDebug() << "Cannot open database:" << db.lastError();
return false;
}
return true;
}

, :
QSqlDatabase::setDatabaseName();

, ,

QSqlDatabase::setUserName();

, ,
QSqlDatabase::setHostName();

QSqlDatabase::setPassword().

,
QSqlDatabase::addDatabase() ( 42.1).
QSqlDatabase::open(). ,
, . ,
QSqlDatabase::lastError(),
QSqlError. qDebug().
, text()
QSqlError .
QSqlDatabase
, .
. QSqlDatabase::tables()
, :
QStringList lst = db.tables();
foreach (QString str, lst) {
qDebug() << "Table:" << str;
}

SQL ( )
SQL
QSqlQuery. () ,
QSqlQuery::exec().
.
QSqlQuery . , SELECT next(),
previous(), first(), last() seek(). next() , previous()
. first() last()

42.

593

. seek() , .
size().
INSERT. ,
. : prepare()
bindValue(). prepare() ,
bindValue(). :
query.prepare("INSERT INTO addressbook (number, name, phone, email)"
"VALUES(:number, :name, :phone, :email);");
query.bindValue(":number", 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(), . 42.2.
, ,
, , .
, 42.2, SQL. , . , :
1
2

"Piggy" ;
"Kermit" ;

"+49 631322187" ;
"+49 631322181" ;

"piggy@mega.de"
"kermit@mega.de"

42.2. SQL. main.cpp. main()

int main(int argc, char** argv)


{
QCoreApplication app(argc, argv);
//
if (!createConnection()) {
return -1;
}
//
QSqlQuery query;

VI. Qt

594
QString

str

= "CREATE TABLE addressbook ( "


"number INTEGER PRIMARY KEY NOT NULL, "
"name
VARCHAR(15), "
"phone VARCHAR(12), "
"email VARCHAR(15) "
");";

if (!query.exec(str)) {
qDebug() << "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)) {
qDebug() << "Unable to make insert operation";
}
str = strF.arg("2")
.arg("Kermit")
.arg("+49 631322181")
.arg("kermit@mega.de");
if (!query.exec(str)) {
qDebug() << "Unable to make insert operation";
}
if (!query.exec("SELECT * FROM addressbook;")) {
qDebug() << "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")).toInt();
strName = query.value(rec.indexOf("name")).toString();
strPhone = query.value(rec.indexOf("phone")).toString();
strEmail = query.value(rec.indexOf("email")).toString();

42.

595

qDebug() << nNumber << " " << strName << ";\t"
<< strPhone << ";\t" << strEmail;
}
return 0;
}

createConnection() , SQL .
exec() QSqlQuery. , . ,
, strF INSERT. arg() QString , .
, , SELECT, query.
. next()
. . , ,
next() false, .
QSqlQuery::value(),
. record().
QSqlRecord,
SELECT . QSqlRecord::indexOf(), .
value() QVariant. QVariant ,
(. 4).
, QVariant::toInt() QVariant::toString().
QSqlRecord. , 42.2
, - , . , , ,
, QSqlRecord::count() QSqlRecord::fieldName() ,
.
, QSqlRecord::field().
QSqlField,
, , , ( QSqlField::name()), ( QSqlField::type()),
( QSqlField::length()) ( QSqlField::value()).

QSqlRecord::contains().

SQL- ( )
QtSql (. 12),
.
.
. Qt

VI. Qt

596

, . .


-
SELECT, QSqlQueryModel. . 42.3 Piggy.
(. 42.2).

. 42.2.

42.3. . main.cpp. main()

int main(int argc, char** argv)


{
QApplication app(argc, argv);
if (!createConnection()) {
return -1;
}
QTableView
view;
QSqlQueryModel model;
model.setQuery("SELECT phone, email "
"FROM addressbook "
"WHERE name = 'Piggy';"
);
if (model.lastError().isValid()) {
qDebug() << model.lastError();
}
view.setModel(&model);
view.show();
return app.exec();
}

42.3 QTableView
QSqlQueryModel. setQuery(), -

42.

597

if
lastError(). QSqlError, , ,
. isValid(). qDebug(). setModel().


QSqlTableModel QSqlQueryModel. ,
. , .
, , removeColumn(). , . 42.3,
.

. 42.3.

42.4. . main.cpp. main()

int main(int argc, char** argv)


{
QApplication app(argc, argv);
if (!createConnection()) {
return -1;
}
QTableView
view;
QSqlTableModel model;
model.setTable("addressbook");
model.select();
model.setEditStrategy(QSqlTableModel::OnFieldChange);
view.setModel(&model);
view.show();
return app.exec();
}

42.4 ,
createConnection() (. 42.1),

598

VI. Qt

QTableView QSqlTableModel. setTable()


. select()

.
.
QSqlTableModel ,
setEditStrategy():
OnRowChange ,

;
OnFieldChange ,

;
OnManualSubmit submitAll(). -

revertAll(), .
, . 42.3
QSqlTableModel::OnFieldChange, setEditStrategy()
.
. setModel() .

rowCount() . , , "" .
for (int nRow = 0; nRow < model.rowCount(); ++nRow) {
QSqlRecord rec
= model.record(nRow);
int
nNumber = record.value("number").toInt();
QString
strName = record.value("name").toString();
...
}


. setFilter(),
, SQL-WHERE. setSort() . :
model.setFilter("name = 'Piggy'");
model.setSort(0, Qt::DescendingOrder);
model.select();

, insertRow(),
,
, setData() .
, OnFieldChange OnRowChange
. , :
model.insertRows(0, 1);
model.setData(model.index(0, 0), 4);

42.

599

model.setData(model.index(0, 1), "Sam");


model.setData(model.index(0, 2), "+49 63145476576");
model.setData(model.index(0, 3), "sam@mega.de");
if (!model.submitAll()) {
qDebug() << "Insertion error!";
}

, , , removeRows(). ,
Piggy :
model.setFilter("name = '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');

, . 42.4.

. 42.4.

VI. Qt

600

42.5. . main.cpp. main()

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(&model);
view.show();
return app.exec();
}

42.5 42.3 setRealtion().


"addressbook",
. QSqlRelation.
"status", "addressbook",
"status" , .

. .
, Qt .
, , ,
: , . .
SQL , ,
. () , , .
Qt , :
, .
,
. SQL , ,
. QSqlQuery.
SQL-
.

43



, .

,
. , . Qt (plug-ins).


, , - ,
. , , ,
(), .
, , . ( )
, .
:
. -

,
, ;
;
-

, , . ,
.
, , .
, , . , , , - .

602

VI. Qt

(
pro), :
TEMPLATE = lib
CONFIG += dll

TEMPLATE , , , , .
CONFIG, , . . Windows dll, Mac OS X dylib
Linux so.
. ,
Tools. pro-
, . :
LIBS
+= -L../../lib/ -lTools
INCLUDEPATH = ../../include

, Tools ,
, , .
. Windows
PATH. :
set PATH=%PATH%;c:\Projects\cpp\lib\win32

Mac OS X:
export DYLD_LIBRARY_PATH=/Projects/cpp/lib/mac/:$DYLD_LIBRARY_PATH

Linux:
export LD_LIBRARY_PATH=/Projects/cpp/lib/x11/:$LD_LIBRARY_PATH

, ,
Windows . Mac OS X
macdeployqt. Linux ,
LD_LIBRARY_PATH.


. . . .
.

. , , ,

. QLibrary. ,
.

43.

603

!
, ,
.

, 43.143.3, , .
43.1. dynlib.pro

TEMPLATE
DESTDIR
QT
SOURCES
HEADERS
TARGET

= lib
= ..
-= gui
= dynlib.cpp
= dynlib.h
= dynlib

, 43.1. TEMPLATE lib.


,
DESTDIR "..".
, , , , -=
gui QT.
43.2. dynlib.h

#include <QString>
extern "C" {
QString oddUpper(const QString& str);
}


.
extern "C" {...}. C++ . oddUpper() ,
. ,
,
, , QLibrary, .

C++ , . "C" .
43.3. dynlib.cpp

#include "dynlib.h"
QString oddUpper(const QString& str)

VI. Qt

604
{
QString strTemp;

for (int i = 0; i < str.length(); ++i) {


strTemp += (i % 2) ? str.at(i) : str.at(i).toUpper();
}
return strTemp;
}

43.3 , .
, 43.4,
, .
(. 43.1).

. 43.1.

43.4. main.cpp

#include <QtGui>
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QLabel
lbl("this is the example text");
QLibrary
lib("dynlib");
typedef QString (*Fct) (const QString&);
Fct fct = (Fct)(lib.resolve("oddUpper"));
if (fct) {
lbl.setText(fct(lbl.text()));
}
lbl.show();
return app.exec();
}

43.4 lbl, . ,
QLibrary , , . , . Windows
dll, UNIX so, MacOS X dylib. , Qt .

43.

605

resolve() ( 43.4). , . void,


. resolve() , , .
. .
show().

(plug-ins)
. , ,
, .
:
Qt;
.

Qt
Qt , , , ,
. . 20. :
QSqlDriverPlugin ;
QPictureFormatPlugin, QImageIOPlugin -

(. 19);
QTextCodecPlugin ;
QStylePlugin (. 26).

QObject, Qt. Qt ,
. QStylePlugin. , 26 CustomStyle, , 43.543.7.
43.5. CustomStylePlugin.h. CustomStylePlugin

class CustomStylePlugin : public QStylePlugin


{
public:
QStringList keys (
) const;
QStyle*
create(const QString &key);
};

, QStylePlugin ( 43.5), keys() create().

VI. Qt

606
43.6. CustomStylePlugin.cpp. keys()

QStringList CustomStylePlugin::keys() const


{
return QStringList() << "CustomStyle";
}

keys() .
CustomStyle ( 43.6).
43.7. CustomStylePlugin.cpp. create()

QStyle* MyStylePlugin::create(const QString &key)


{
if (key == "CustomStyle")
return new CustomStyle;
return 0;
}
Q_EXPORT_PLUGIN2(CustomStylePlugin)

create() . , ( 43.7).
, cpp-
Q_EXPORT_PLUGIN2, 43.7.
43.8. main.cpp

void main(int argc, char** argv)


{
...
QApplication::setStyle(QStyleFactory::create("CustomStyle"));
...
}

.
QStyleFactory ( 43.8).
Qt ,
, . < Qt>/plugins/styles.
!
Qt
, ,
. , Windows
<MyApplication>/imageformats/ , <MyApplication>/
sqldrivers/ . Linux ,
Mac OS X macdeployqt, . , , WebKit,
, JPG-, GIF-
TIFF-, .

43.

607


(. ), . QPluginLoader,
. instance(),
.
, . , , unload().
, . 43.2, ,
( 43.943.14).
.

. 43.2. ,

43.9. interfaces.h

#ifndef _interfaces_h_
#define _interfaces_h_
class QString;
class QStringList;
// ======================================================================
class StringInterface {
public:
virtual ~StringInterface() {}
virtual QStringList operations() const = 0;
virtual QString operation(const QString& strText,
const QString& strOperation
) = 0;
};
Q_DECLARE_INTERFACE(StringInterface,
"com.mysoft.Application.StringInterface/1.0"
)
#endif //_interfaces_h_

VI. Qt

608

, ( 43.9).
StringInterafce, , . :
operations() ;
operation() .

, C++
, , , .
Q_DECLARE_
INTERFACE(), -, MOC .
QPlugLoader ,
. ,
:
;
;
;
.
43.10. PluginsWindow.h

#ifndef _PluginsWindow_h_
#define _PluginsWindow_h_
#include <QMainWindow.h>
#include "interfaces.h"
class QLabel;
class QMenu;
// ======================================================================
class PluginsWindow : public QMainWindow {
Q_OBJECT
private:
QLabel* m_plbl;
QMenu* m_pmnuPlugins;
public:
PluginsWindow(QWidget* pwgt = 0);
void loadPlugins(
);
void addToMenu (QObject* pobj);
protected slots:
void slotStringOperation();
};
#endif //_PluginsWindow_h_

43.

609

PluginsWindow QMainWindow ( 43.10). .


43.11. PluginsWindow.cpp.

PluginsWindow::PluginsWindow(QWidget* pwgt/*=0*/) : QMainWindow(pwgt)


{
m_plbl
= new QLabel("this is the test text");
m_pmnuPlugins = new QMenu("&PluginsOperations");
loadPlugins();
setCentralWidget(m_plbl);
menuBar()->addMenu(m_pmnuPlugins);
}

, 43.11, .
( m_plbl) , ( m_pmnuPlugins) addMenu() . loadPlugins() .
43.12. PluginsWindow.cpp. loadPlugins()

void PluginsWindow::loadPlugins()
{
QDir dir(QApplication::applicationDirPath());
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()));
}
}

. , plugins, . QDir ( 43.12).


QPluginLoader. ,
QPluginLoader instance(), QObject
addToMenu(), .
43.13. PluginsWindow.cpp. addToMenu()

void PluginsWindow::addToMenu(QObject* pobj)


{
if (!pobj) {

VI. Qt

610
return;
}

StringInterface* pI = qobject_cast<StringInterface*>(pobj);
if (pI) {
QStringList lstOperations = pI->operations();
foreach (QString str, lstOperations) {
QAction* pact = new QAction(str, pobj);
connect(pact, SIGNAL(triggered()),
this, SLOT(slotStringOperation())
);
m_pmnuPlugins->addAction(pact);
}
}
}

addToMenu() , . . ( 43.13). , .
, , qobject_cast<StringInterface*>. , qobject_cast<T>
. , ,
operations(), lstOperations.
, , .
slotStringOperation() .
43.14. PluginsWindow.cpp. slotStringOperation()

void PluginsWindow::slotStringOperation()
{
QAction* pact = qobject_cast<QAction*>(sender());
StringInterface* pI = qobject_cast<StringInterface*>(pact->parent());
m_plbl->setText(pI->operation(m_plbl->text(), pact->text()));
}

, 43.14, sender() ,
. QAction. parent() . operation(), .
,
.


, , ,
.

43.

611

43.15. MyPlugin.pro

TEMPLATE
CONFIG
QT
DESTDIR
SOURCES
HEADERS
TARGET

= lib
+= plugin
-= gui
= ../plugins
= MyPlugin.cpp
= MyPlugin.h \
../Application/interfaces.h
= myplugin

CONFIG pro- plugin,


HEADERS interfaces.h ( 43.15).
43.16. MyPlugin.h

#ifndef _MyPlugin_h_
#define _MyPlugin_h_
#include <QObject>
#include "../Application/interfaces.h"
// ======================================================================
class MyPlugin : public QObject, public StringInterface {
Q_OBJECT
Q_INTERFACES(StringInterface)
private:
QString oddUpper(const QString& str);
public:
virtual ~MyPlugin();
virtual QStringList operations(
) const;
virtual QString
operation (const QString&, const QString&);
};
#endif //_MyPlugin_h_

MyPlugin, 43.16, :
QObject StringInterface. Q_INTERFACES() ,
MOC .
, C++ " " ,
, , .
43.17. MyPlugin.cpp. operations()

/*virtual*/ QStringList MyPlugin::operations() const


{
return QStringList() << "oddUpper" << "lower";
}

VI. Qt

612

, 43.17,
. : oddUpper lower.
43.18. MyPlugin.cpp. oddUpper()

QString MyPlugin::oddUpper(const QString& str)


{
QString strTemp;
for (int i = 0; i < str.length(); ++i) {
strTemp += (i % 2) ? str.at(i) : str.at(i).toUpper();
}
return strTemp;
}

oddUpper(), 43.18, .
(. 43.3), .
43.19. MyPlugin.cpp. operation()

/*virtual*/ QString MyPlugin::operation(const QString& strText,


const QString& strOperation
)
{
QString strTemp;
if (strOperation == "oddUpper") {
strTemp = oddUpper(strText);
}
else if (strOperation == "lower") {
strTemp = strText.toLower();
}
else {
qDebug() << "Unsupported operation";
}
return strTemp;
}

43.19 operation(), .
, , . , .
cpp- Q_EXPORT_PLUGIN2(). Q_EXPORT_PLUGIN2() , Qt:
Q_EXPORT_PLUGIN2(StringInterface, MyPlugin)

43.

613

,
. , ,
, , .
, . ,
, . .
, . ,
.
Qt . resolve() .
.
, .
Qt :
;
.

Qt
, . , .

Qt

QPluginLoader, , . ,

, ,
. Q_DECLARE_INTERFACE. , , ,
, qobject_cast<T>.
, , .
: QObject , .
Q_INTERFACES, MOC .

44

Qt
API
.
! .
!
, .

. .
" "

, Qt , , , , .
. , ,
. , (. 43) .
, ,
, . , ,
:
#if defined(Q_WS_WIN)
// Windows
#elif defined(Q_WS_X11)
// Unix
#elif defined(Q_WS_MAC)
// MacOS
#else
//
#endif

Qt , . 44.1 .
:
#ifdef Q_OS_WIN
// Windows
#else
#error "Not implemented!"
#endif

44. Qt API

615

44.1.

Q_OS_AIX

AIX (Advanced Interactive eXecutive) ,


UNIX System V, IBM

Q_OS_FREEBSD

FreeBSD UNIX- ,
UNIX- AT&T

Q_OS_IRIX

IRIX UNIX SGI (Silicon Graphics Inc.)

Q_OS_LINUX

Linux , UNIX

Q_OS_MAC

Mac OS X Apple Macintosh

Q_OS_SOLARIS

SOLARIS c UNIX,
Sun Microsystems

Q_OS_WIN32

32- Windows Microsoft

Q_OS_WIN64

64- Windows Microsoft


, C++ . : Q_CC_INTEL, Q_CC_MSVC, Q_CC_MINGW,
Q_CC_BOR .

qmake ,
. pro-
,
( Mac OS X (frameworks)) . Mac OS X
mm-, Objective C++:
mac {
DESTDIR = ../../lib/mac
LIBS += -lAnyMacOSXLib -framework AnyFrameworkName
SOURCES += myfile_mac.mm
}
win32 {
DESTDIR = ../../lib/win32
LIBS += -lAnyWin32Lib
SOURCE += myfile_win.cpp
}
!win32:!mac {
DESTDIR = ../../lib/x11
LIBS += -lAnyUnixLib
SOURCES += myfile_lin.cpp
}

.
, , :

VI. Qt

616
win32-msvc.net {
SOURCES += MyDotNetFile_win.cpp
}

,
"{}" ":". , , Windows :
win32:debug:CONFIG += console

qmake 3.

Windows API
, . 44.1,
GDI (Graphical Device Interface, ) Windows. Windows API.

. 44.1. GDI

44.1. main.cpp. WinAPI

class WinAPI : public QWidget {


protected:
virtual bool winEvent(MSG* pmsg, long* result)
{
QString str1 = "Windows Version = "
+ QString::number(QSysInfo::WindowsVersion);
QString str2 = "Windows Message";
switch(pmsg->message) {
case WM_RBUTTONDOWN:
::MessageBox(winId(),
(const WCHAR*)str1.utf16(),
(const WCHAR*)str2.utf16(),
MB_OK | MB_ICONEXCLAMATION
);

44. Qt API

617

break;
default:
;
}
return QWidget::winEvent(pmsg, result);
}
virtual void paintEvent(QPaintEvent*)
{
QPainter painter(this);
HDC
HBRUSH
HPEN
QString
TEXTMETRIC

hdc
hBrush
hPen
str
tm;

=
=
=
=

painter.paintEngine()->getDC();
::CreateSolidBrush(RGB(255, 0, 255));
::CreatePen(PS_SOLID, 2, RGB(0, 0, 128));
"GDI Drawing";

::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(hBrush);
::DeleteObject(hPen);
painter.paintEngine()->releaseDC(hdc);
}
public:
WinAPI(QWidget* pwgt = 0) : QWidget(pwgt)
{
}
};

44.1 Windows
winEvent(). Qt,
true. , ,
Windows.
, ,
MessageBox() Windows API, .
Windows, winId(). ,
Windows, , HWND
( ). HWND.

VI. Qt

618

paintEvent()
GDI. getDC() QPaintEngine
( 44.1). HDC ( Device Context,
), GDI, .
releaseDC() QPaintEngine GDI ( hdc), . QString (const
WCHAR*)str.utf16(). 44.244.3 ,
, Windows.
44.2. QString

++ Standard String

std::wstring wstr = qstr.toStdWString()

BSTR (OLE String)

BSTR bstr = ::SysAllocString(qstr.utf16())

8bit (LPCSTR)

LPCSTR lstr = qstr.toLocal8Bit().constData()

LPCWSTR

LPCWSTR wstr = qstr.utf16()

CString (MFC)

CString mfcstr = qstr.utf16()

. 44.3 .
44.3. QString

++ 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::fromUtf16((LPCTSTR(mfcstr)))

Linux
Windows, UNIX Qt
. QWidget x11Event(),
X Window. ,
.
Qt, true.

Mac OS X
Mac OS X
Objectve C++. , C++. Objective C C++. ,

44. Qt API

619

C++, h- C++
Objective ++, Q_WS_MAC .
C++ ( Qt) . -,
Objective C - , . . , C++ . C++ Qt
, .
Objective C , , , , ,
, . . Qt
C++. Objective C
, ,
C++, .
Objective C C - , . . , C, Objective C , C++ . GCC , , Windows MinGW.
, "" Apple
Mac OS X, iPhone, iPad iPodtouch . ,
. 44.2, (
) Mac OS X.

. 44.2. Mac OS X

44.2. MacButton.pro

TEMPLATE = app
TARGET
= MacButton
mac: OBJECTIVE_SOURCES += MacButton.mm
SOURCES += main.cpp
HEADERS += MacButton.h
mac: LIBS += -framework Cocoa

pro- ( 44.2) Objective C++


OBJECTIVE_SOURCES "Cocoa" LIBS.
44.3. main.cpp

#include <QtGui>
#include "MacButton.h"

VI. Qt

620
int main(int argc, char** argv)
{
QApplication app(argc, argv);
#ifdef Q_WS_MAC
MacButton cmd;
cmd.show();
#else
QLabel label("This example requires Mac OS X");
label.show();
#endif
return app.exec();
}

( 44.3) Q_WS_MAC , ( MacButton) , Mac OS X.


.
44.4. MacButton.h

#ifndef _MacButton_h_
#define _MacButton_h_
#include <QtGui>
#ifdef Q_WS_MAC
#import <qmaccocoaviewcontainer_mac.h>
// ======================================================================
class ButtonContainer : public QMacCocoaViewContainer {
Q_OBJECT
public:
ButtonContainer(QWidget* pwgt = 0);
QSize sizeHint() const;
};
// ======================================================================
class MacButton : public QWidget {
Q_OBJECT
public:
MacButton(QWidget* pwgt = 0);
};
#endif // Q_WS_MAC
#endif //_MacButton_h_

44. Qt API

621

( 44.4) ButtonContainer, QMacCocoaViewContainer,


Mac OS X. qmaccocoaviewcontainer_mac.h,
#import. Objective C
#include C, ,
h- , :
#ifndef _MyFile_h_
#define _MyFile_h_

, , ,
MacButton,
ButtonContainer.

, h-
Q_WS_MAC.
44.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];
}

( 44.5)
Objective C. "Cocoa" ,
( NSButton) . Objective
alloc, init. alloc
new C++, init . (
NSButton). :
setButtonType NSSwitchButton ;
setTitle ;
setState YES ( C++ YES
true) .

VI. Qt

622

( pcmd) "Cocoa" setCocoaView().


release ( pcmd) , , ButtonContainer
. relase ( ppool).

Objective C, , , . , . ,
Objective C , 2 , ,
.
Objective C,
, C++, .
44.6. ButtonContainer.mm. sizeHint()

QSize ButtonContainer::sizeHint() const


{
return QSize(150, 40);
}

sizeHint() ( 44.6) ,
.
44.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);
}

44.7 MacButton.
Mac OS X NSString.
NSString QString :
NSString* ns
QString

= @"ConvertMe";

str = QString::fromUtf8([ns UTF8String]);


, , , , - -

44. Qt API

623

. -
, , , , .
,
,
,
. QSysInfo , :
WindowsVersion Windows. -

: WV_XP, WV_VISTA, WV_WINDOWS7, CE- : WV_CE_5, WV_CE_6


. .;
MacintoshVersion Mac OS. -

: MV_TIGER, MV_LEOPARD, MV_SNOWLEOPARD . .;


s60Version() S60. :

SV_S60_5_1, SV_S60_5_2 . .;
symbianVersion()

Symbian. : SV_SF_3, SV_SF_4 . .


,
Linux. , Linux. , Windows Mac OS X:
#ifdef Q_WS_WIN
qDebug() << "Windows version:" << QSysInfo::WindowsVersion;
#endif
#ifdef Q_OS_MAC
qDebug() << "Mac version:" << QSysInfo::MacintoshVersion;
#endif

QSysInfo ,
. , QSysInfo::
ByteOrder. :
if

(QSysInfo::ByteOrder == QSysInfo::BigEndian) {
qDebug() << "System is big endian";

}
else {
qDebug() << "System is little endian";
}

Qt . , , Qt. pro-
,
, .

45

Qt Designer.

...
-

Qt Designer (Rapid Application Development, RAD). ,


WYSIWYG (What You See Is What You Get, "
, "). , , ,
, . Qt Designer
C++. , Qt, Qt Designer , .
Qt Designer , QLCDNumber.

Qt Designer
Qt Designer .
: , . .,
, .
.
. 45.1 Qt Designer. Widget Box (),
, .
.
:
Object Inspector () .

. , Property Editor
( ) ;
Property Editor ( ) . -

, , / . .;
Signal/Slot Editor ( )

45. Qt Designer.

625

Resource Editor ( ) -

;
Action Editor ( ) ,
.
New Form ( )
(. 45.1). , Show this Dialog on Startup (
).
File | New Form... ( | ) ""
<Ctrl>+<>.

. 45.1. Qt Designer

New Form ( ) .
Widget (), (. 45.2).
Qt Designer . Qt Designer (. 45.1)
45.1.

Edit Widgets (
)

,
, , ,

VI. Qt

626

45.1 ()

Edit Signals/Slots
(
/)

Edit Buddies (
)

""
. ,
,

Edit Tab Order (



)

. 45.2.

Property Editor ( ), ,
windowTitle ( ) Form, ,
"DesignedWidget" (. 45.3). objectName ( )
, . "MyForm".

uic ui- C++,
, .

45. Qt Designer.

627


, ,
,
.
.

File | Save Form As... ( |
) "" <Ctrl>+<S>.

. 45.3. .


,
Widget Box () (. . 45.2). , .
, Buttons () PushButton (),
Input Widgets ( ) Horizontal Slider ( ), Display Widgets ( ) LCDNumber ( )
. , , Object Inspector (),
(. 45.4). .

. 45.4. Object Inspector

, , Object Inspector ()
. text () Property
Editor ( ) "&Reset", objectName () "m_pcmdReset".

VI. Qt

628

, objectName ()
"m_pcmdQuit", text () "&Quit". , objectName
(), : ,
. (. . 45.4). , . 45.5.

. 45.5.

(layout)
, .
, , , . .
. ,
. , , Lay out | Lay out Vertically (| ) "" <Ctrl>+<2>.
Reset () Quit ().
, , (Spacer). Widget Box () Spacers () Vertical Spacer ( )
. ,
. 45.6.
,
.
MyDialog Object Inspector ().
Lay out |
Lay out Horizontally ( | )
"" <Ctrl>+<1>. , . 45.7. , .

45. Qt Designer.

629

. 45.6.

. 45.7.


.
<Tab> . ,
Edit | Edit Tab Order ( | )
. ,

VI. Qt

630

. 45.8.

. 45.8. , , .


, Edit | Edit Signals/Slots ( | /) <F4>.
,
, , , .
, . , .
Configure Connection ( ), . valueChanged(int), display(int) (. 45.9).
Quit (),
close(). ,
, ,
. , . 45.10.
Configure
Connection ( ) clicked().
close(), Show all signals and slots (
),
.
,
Form | Preview ( | ). -

45. Qt Designer.

631

, ,
.
, , .

. 45.9.

. 45.10.

, .
File | Save Form As... ( |
...), ,
MyFrom.ui.

VI. Qt

632



,
, ui- C++.
.
, QWidget, ,
Promote to.... (. 45.11)
, .
, , , , . ,
Add Promote.

. 45.11.


, . Qt .
, (direct approach) .
Ui::MyForm::setupUi() , 45.1.
45.1.

#include "ui_MyForm.h"
#include <QtGui>

45. Qt Designer.

633

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 ( 45.2).
45.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 ()

VI. Qt

634

( m_cmReset) c slotReset(). , ,
Qt Designer,
. , .
, (multiple inheritance approach).
, ,
. 45.3.
45.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);
}
};
#endif //_MyForm_h_

45.3, MyForm QWidget,


, Qt Designer.

, .
FORMS. , pro-
:
TEMPLATE
HEADERS
FORMS
SOURCES
win32:TARGET

=
+=
+=
+=
=

app
MyForm.h
MyForm.ui
main.cpp
../MyForm

45. Qt Designer.

635

, , (MyForm.ui)
, make- :
qmake
make

ui- h- ui_.
,
, . 45.12.

. 45.12.


, . , XML-
(ui-) , .
QUiLoader, QtUiTools, ,
.
, 45.145.3.
45.4. LoadMyForm.pro

TEMPLATE
= app
CONFIG
+= uitools
HEADERS
= LoadMyForm.h
SOURCES
= main.cpp
RESOURCES
= resource.qrc
win32:TARGET = ../LoadMyForm

VI. Qt

636

( 45.4) QtUiTools,
CONFIG. ,
RESOURCES. , FORMS , . . XML- .
45.5. main.cpp

#include <QApplication>
#include "LoadMyForm.h"
int main(int argc, char** argv)
{
QApplication app(argc, argv);
LoadMyForm
wgt;
wgt.show();
return app.exec();
}

, 45.5,
LoadMyForm.
45.6. LoadMyForm.cpp.

#ifndef _LoadMyForm_h_
#define _LoadMyForm_h_
#include <QtGui>
#include <QtUiTools>
// ======================================================================
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(&file);
if (pwgtForm) {
resize(pwgtForm->size());
m_psld = pwgtForm->findChild<QSlider*>("m_sld");
m_plcd = pwgtForm->findChild<QLCDNumber*>("m_lcd");

45. Qt Designer.

637

QPushButton* pcmdReset =
pwgtForm->findChild<QPushButton*>("m_cmdReset");
connect(pcmdReset, SIGNAL(clicked()), SLOT(slotReset()));
QPushButton* pcmdQuit =
pwgtForm->findChild<QPushButton*>("m_cmdQuit");
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);
}
};
#endif //_LoadMyForm_h_

LoadMyForm QWidget ( 45.6). QSlider QLCDNumber ,


(m_psld m_plcd). QUiLoader ( puil) this.
, QFile
":/MyForm.ui". load()
.
, , ,
XML- , .
. pwgtForm, resize().
,
findChild<*>(""), QObject. ( m_psld), (
m_pcd), Reset ( pcmdReset) Quit ( pcmdQuit).
clicked() Reset slotReset(), .
Quit clicked() quit()
qApp. pwgtForm LoadMyForm phbxLayout.

. Qt Designer
.

638

VI. Qt

, . ,
.
. , ,
.
Qt Designer .
:
;
;
;
ui-.

46


. . .
:
, ?
?
.
?
.
?
.
, , ,
!

,
.
.
. .
, , . , , ,
.
. . ,
, . ,
, , , .
.
, . , , . ,
. ,
, . . , .
, ,
. , , .
, . . - , . ,

640

VI. Qt

, :
. , , . . , , , , .
, .
Qt QtTest,
, .
"" .
, , (unit tests).

, . ,
, .
(system test), . . GUI, , (drag&drop) . ., RoboCute, : www.neonway.com/robocute.


.
, .
.
: ,
. ,
. : (25, 0), (12, 15), (2007,
2007) (12, 5). , , . ,
. :
Test_. -

, MyClass,
Test_MyClass;
() .
46.1. . test.cpp

#include <QtTest>
#include "MyClass.h"
// ======================================================================
class Test_MyClass : public QObject {
Q_OBJECT

46.

641

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"

46.1 , min()
max() MyClass.
QTest. QObject , , QOBJECT.
,
private.
QCOMPARE() , , . ,
.
main(), . , Qt
QTEST_MAIN().
,
MOC.
.
46.2. MyClass.cpp

#ifndef MyClass_h_
#define MyClass_h_

VI. Qt

642

// ======================================================================
class MyClass {
public:
int min(int n1, int n2)
{
return n1 < n2 ? n1 : n2;
}
int max(int n1, int n2)
{
return n1 > n2 ? n1 : n2;
}
};
#endif //MyClass_h_

MyClass ( 46.2).
46.3. TestLib.pro

SOURCES = test.cpp
HEADERS = MyClass.h
CONFIG += qtestlib
TARGET = ../TestLib

pro- CONFIG qtestlib.


,
.
, . .
, . ,
, . min()
max() MyClass . . :
********* Start testing of Test_MyClass *********
Config: Using QTest library 4.2.2, Qt 4.2.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() . -.

46.

643

. ,
, : "FAIL!", "Test_MyClass::min()"
"Test_MyClass::max()", (Actual) (Expected). !
, , .
MyClass , 46.2. .
:
********* Start testing of Test_MyClass *********
Config: Using QTest library 4.2.2, Qt 4.2.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.
46.4. test.cpp. Test_MyClass

class Test_MyClass : public QObject {


Q_OBJECT
private slots:
void min_data();
void max_data();
void min();
void max();
};

, 46.4, :
min_data() max_data(), .
46.5. test.cpp. min_data()

void Test_MyClass::min_data()
{
QTest::addColumn<int>("arg1");
QTest::addColumn<int>("arg2");
QTest::addColumn<int>("result");

VI. Qt

644
QTest::newRow("min_test1")
QTest::newRow("min_test2")
QTest::newRow("min_test3")
QTest::newRow("min_test4")

<<
<<
<<
<<

25 << 0 << 0;
-12 << -5 << -12;
2007 << 2007 << 2007;
-12 << 5 << -12;

46.5 min_data(),
. QTest::addColumn().
, QTest::newRow(). , , .
, << : min().
46.6. test.cpp. max_data()

void Test_MyClass::max_data()
{
QTest::addColumn<int>("arg1");
QTest::addColumn<int>("arg2");
QTest::addColumn<int>("result");
QTest::newRow("max_test1")
QTest::newRow("max_test2")
QTest::newRow("max_test3")
QTest::newRow("max_test4")

<<
<<
<<
<<

25 << 0 << 25;


-12 << -5 << -5;
2007 << 2007 << 2007;
-12 << 5 << 5;

max_data() ( 46.6) min_data()


(. 46.5).
.
46.7. test.cpp. min()

void Test_MyClass::min()
{
MyClass myClass;
QFETCH(int, arg1);
QFETCH(int, arg2);
QFETCH(int, result);
QCOMPARE(myClass.min(arg1, arg2), result);
}

, min(),
46.7, . QFETCH() arg1, arg2,
result . , , ,
. -

46.

645

QCOMPARE(). .
46.8. test.cpp. max()

void Test_MyClass::max()
{
MyClass myClass;
QFETCH(int, arg1);
QFETCH(int, arg2);
QFETCH(int, result);
QCOMPARE(myClass.max(arg1, arg2), result);
}

max() 46.8
min(), , MyClass::max()
MyClass::min().
main() QTEST_MAIN()
, MOC:
QTEST_MAIN(Test_MyClass)
#include "test.moc"



QtTest . ,
QLineEdit. , .
46.9. test.cpp

#include <QtTest>
#include <QtGui>
// ======================================================================
class Test_QLineEdit : public QObject {
Q_OBJECT
private slots:
void edit();
};
// ---------------------------------------------------------------------void Test_QLineEdit::edit()
{
QLineEdit txt;
QTest::keyClicks(&txt, "ABCDEFGH");

VI. Qt

646
QCOMPARE(txt.text(), QString("ABCDEFGH"));
QVERIFY(txt.isModified());
}
QTEST_MAIN(Test_QLineEdit)
#include "test.moc"

edit() QLineEdit ( 46.9).


"ABCDEFGH", QTest::keyClicks(),
.
, , ,
. keyClick(), keyPress() keyRelease(),
, Qt::Key.
(Shift, Ctrl Alt)
.
QCOMPARE() , .
, isModified() true.
QVERIFY(). , , . .
QTest , , . :
mouseClick() ;
mouseDClick() ;
mousePress() ;
mouseRelease() .

, . , , .
mouseMove(), . , ,
:
QPushButton cmd:
QTest::mouseClick(&cmd, Qt::LeftButton);

QTestEventList, simulate(). ,
: , :
QTestEventList lst;
lst.addKeyClicks("ABCDE");
lst.addDelay(1000);
lst.addKeyClick(Qt::Key_Backspace);
QLineEdit txt;
lst.simulate(&txt);

46.

647


QtTest .
. ,
, MyTest::max() ( 46.2),
:
TestLib max

. 46.1 , .
46.1.

-o filename

file

-silent

-v1

-v2

-v1 , QCOMPARE()
QVERIFY()

-vs

-xml

XML

-eventdelay ms

( ).

, . , . .
, . QObject.
QTEST_MAIN(), main() .
QCOMPARE() .
, , .
QVERIFY() . true, . ,
.
, , QtTest .
private .
, , _data. . QFETCH()
.
QtTest .

47

WebKit
, ... , ,
.

.
. , , , . Web-, ,
Web.
, Web,
Web-. , HTML- Web- . Web .
, ,
Web-, , , . , , iTunes (. 47.1) Apple. iPod iPhone
, Mac OS X, Windows.
www.apple.com/itunes/download/.
Web-, iTunes . . .
, , , ,
, . , iTunes Web- WebKit,
.
. , , Web- , , , , Web, -

47. WebKit

649

, Web-, Google,
Yahoo .
WebKit?

. 47.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.

650

VI. Qt

?
, Web-, , ,
Web-. "-",
Web- Web-. ,
. , , , . .
, . , MIME-, , , .
, , .
Qt WebKit . .


WebKit , Web-, Web. .
WebKit . WebKit Web-.
, WebKit
, Web-.
, MIME-.
, WebKit
. "", , , Qt, Web-
.
WebKit ,
, Web- ( ). ,
, .
Web- , :
1. QWebView.
2. .
3. .
! ,
(. 47.2).

47. WebKit

651

. 47.2. Web-

47.1. Web-

#include <QtGui>
#include <QtWebKit>
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QWebView
webView;
webView.load(QUrl("http://www.bhv.ru"));
webView.show();
return app.exec();
}

QWebView WebKit,
. , .
. 47.1
Web- (webView) load(),
. , QUrl. show() .

VI. Qt

652


, (.pro) QT += webkit.

, Web- . , " "


. , , . , . , . . , .

Web-
, , Web, :
Web-;
;
.


- ,
, .
Web-, .
, , , WebKit , ,
load(). . , , , , . www.bhv.ru, http://www.bhv.ru.
.


WebKit
Web-. ,
, , . WebKit QWebHistory.
QWebView history(). QWebHistoryItem. . , . , , ,
.

47. WebKit

653

clear()
QWebHistory.
, Web- , . , Web- , ,
. Web-
, . QWebHistory
back() forward(), , . . QWebView
, .


, ,
( ), ,
, CSS, Web-, . Web , .
, .
, ,
WebKit . , , .
. QWebView loadFinished(), .
, . , ,
.
, , loadProgress()
QWebView. 0 100, .

Web-,
, Web-, . 43.7.
47.2. main.cpp

#include <QtGui>
#include "WebBrowser.h"
int main(int argc, char** argv)
{
QApplication app(argc, argv);
WebBrowser
webBrowser;
webBrowser.show();
return app.exec();
}

654

VI. Qt

. 47.3. Web-

( 47.2) Web-
(webBrowser).
47.3. WebBrowser.h

#ifndef _WebBrowser_h_
#define _WebBrowser_h_
#include <QWidget>
class QLineEdit;
class QWebView;
class QPushButton;
// =============================================================
class WebBrowser : public QWidget{
Q_OBJECT
private:
QLineEdit*
m_ptxt;
QWebView*
m_pwv;
QPushButton* m_pcmdBack;
QPushButton* m_pcmdForward;

47. WebKit

655

public:
WebBrowser(QWidget* wgt = 0);
private slots:
void slotGo
(
);
void slotFinished(bool);
};
#endif //_WebBrowser_h_


: ( m_ptxt), Web ( m_pwv) ( m_pcmdForward m_pcmdBack). : slotGo()
slotFinished(). , ,
, .
47.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*
QPushButton*
QPushButton*
QPushButton*

pprb
pcmdGo
pcmdStop
pcmdRefresh

=
=
=
=

new
new
new
new

QProgressBar;
QPushButton("&Go");
QPushButton("&Stop");
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);

VI. Qt

656
QVBoxLayout* playout = new QVBoxLayout;
playout->addLayout(phbx);
playout->addWidget(m_pwv);
playout->addWidget(pprb);
setLayout(playout);
slotGo();
}

( 47.4) Web- . ( m_ptxt)


. Web- ( m_pwv)
( m_pcmdForward) ( m_pcmdBack). Web- , . .
. setEnabled(),
Web- back() forward().

( pprb). setValue() Web-
loadProgress().
, ,
Go, Stop Refresh. Go .
slotGo() ,
<Enter> . Stop
Web-, Web stop(). Refresh Web-, Web-, .
slotGo().
47.5. WebBrowser.cpp. slotGo()

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()));
}

slotGo() ( 47.5). ,
load(), .
, , , . ftp://, http://
gopher://, , , -

47. WebKit

657

http:// .
, load().
47.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().toString());
m_pcmdBack->setEnabled(m_pwv->page()->history()->canGoBack());
m_pcmdForward->setEnabled(m_pwv->page()->history()->canGoForward());
}

47.6 slotFinished(), . , . . , setHtml() Web- .


, , , . ,
.
, . ,
, ( m_ptxt), . url() Web- ( m_pwv).
.
, , QWebHistory
canGoBack() canGoForward().
.

Web-.
WebKit , Web-,
. Qt WebKit QWebView,
.

48


Qt Creator
,
,
.

(Integrated Development Environment IDE)


, .
. Nokia
. , Nokia . Qt Creator Qt SDK.
Qt Creator , Qt- C++
QML.
. IDE Qt Creator , . 48.1.
Qt Help,
Qt. Qt
, Qt Creator.
Qt Creator , ,
. Windows MinGW
(. Minimalist GNU for Windows), Qt SDK.

. 48.1. Qt Creator

48. Qt Creator

659


. ,
.
, , , . , , .
Qt Designer (. 45)
, .


Qt Creator
(. 48.2), . .
.
, .

. 48.2. Qt Creator

"Hello Qt Creator"
1. Qt Creator.

660

VI. Qt

, , ( pro-). , - Qt Creator,
, pro- Qt Creator.
Qt Creator , . "-", , .
Qt Creator .
(. 48.3) Qt
Widget, :
GUI Qt Qt;
Qt .

. 48.3.

, GUI Qt ....
, . 48.4, ,
MyApp, , Qt Creator
.

48. Qt Creator

661

. 48.4.

, . ,
, ... .
.
Qt, ,
(. 48.5).
. Qt.
, Qt,
. .

(. 48.6) , (.h),
(.cpp) (.ui). ,
Qt Designer, 45,
, . , . . Qt Designer.
,

662

VI. Qt

. 48.5.

. 48.6.

48. Qt Creator

663

(. 48.7). , , Qt Creator MyApp .


,
. 48.8.

. 48.7.

. 48.8.

. . 48.9 , , ,
.
.
,

664

VI. Qt
. 48.9.

. 48.10.

, . 48.9, (. 48.10)
... , , .... ...,
(. . 48.3),
. .
. -

48. Qt Creator

665

... (. . 48.10),
.

Qt Creator
Qt Creator.

. 48.11. Qt Creator

Qt Creator
(. 48.11):
;

;
(, , . .)

;
;
( ,

).
.

VI. Qt

666


( )
. , , ,
. ,
.
,
Qt Creator. ,
.


, . 48.8. ,
,
.
.


,
.
. , .
(. 48.12).

. 48.12.

48. Qt Creator

667


, .
,
Qt , , .
, , Symbian MeeGo.
, . .
.

. 48.13.

,
(. 48.13). , . , . , Qt Creator, .
. (.h, .cpp) .
Qt Designer (.ui).
drag & drop, .
widget.ui, Qt Designer (. 48.14).
. , Filter () "Label". , ,
. .
Display Widgets Label .
"TextLabel". ,
, .
,
. "Hello Qt Creator" (. 48.15).
(. 48.16).
Qt (. . 48.5),
, Nokia N900 (. 48.17).

668

VI. Qt

. 48.14. Qt Designer

. 48.15.

. 48.16. "Hello Qt Creator"

48. Qt Creator

669

. 48.17. "Hello Qt Creator"


, , . , , .

?
Qt Creator
,
. , , , , , .
. , ,
/*, - , , *) */, , . . . , , fir
for, , .
, .
Qt Creator :
;
;
;
;
-;
;
-;
.

, ,
| | .

VI. Qt

670



. Qt Creator . : , , , . ,
.
(. 48.18), , .

. 48.18.


/ , , Qt Creator
.
, <Ctrl>+<>.
, , , , . . 48.19.

. 48.19.



, Qt, , INCLUDEPATH (.pro).

48. Qt Creator

671

, Qt Creator.
/ (. 48.20).

. 48.20. | /

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

. 48.21.

VI. Qt

672

- , .
| / | (. . 48.20)
:
;
;
;
.

,
. 48.22. . (. 4), . , ,
.
cpp h, .

. 48.22.


(. 48.23). ,
, . . ,
,
. :
( "*").
Locator (). , ,
Qt. , ,
<Ctrl>+<K>. , :
"l" ;
":" ;
"o" ;
"?" ;
"f" , ;

48. Qt Creator

673

"a" , ;
"p" .

. 48.24 .

. 48.23.

. 48.24.

, , . ,
,
(. 48.25), <Ctrl>+<Shift>+<U>. ,
(. . 48.25).
, , , . ,
. Qt Creator . , ,
. |
<Ctrl>+<Shift>+<R> (. 48.26).

674

VI. Qt

. 48.25.

. 48.26.

48. Qt Creator

675

, , ,
. .


,
,
. .


, <Shift>, , , . <Shift>
<Alt> , (. 48.27).

. 48.27. <Alt>


( . 48.28),
<Ctrl>+<I>, , .

. 48.28. <Ctrl>+<I>


,
.
<Ctrl>+</>,
, . 48.29.

. 48.29. <Ctrl>+</>

VI. Qt

676


, (.h) - ,
. .
: ,
<F2>, (. 48.30).
,
.

. 48.30. <F2>

, . , , . Qt Creator ,
<F2>,
.

<Ctrl> ( Windows Linux) <Command> ( Mac OS X)
, , , Web-.
, <F2>. , , .

,
. .
, <F1>,
, . 48.31.

. 48.31. <F1>

48. Qt Creator

677


, - ,
Qt Creator , .
<Alt>+<V>, <Alt>+<I>.



3
GDB. Qt Creator GDB . .
, ,
, . .
Qt Creator : <F5> , Qt Creator
(. 48.32).

. 48.32.

, ,
. , ,
.

VI. Qt

678

. , .
,
, " ++".
, .
:
;
;
;
.



. , , ,
. , int float , .
"", . ,
,
, .


,
C++. , ,
. .
. , ,
(. 48.33). ,
- . ,
, . , . , , .
, . , .
. , . 48.33, , return
, .
- , .
,
:
1. , .
2. , , ,
.

48. Qt Creator

679

. 48.33.

3. ,
. - .
4. ,
- . , "" .


.
, . .
, . , , , . , . .
(, Linux ).
. 48.34 : ,
. , ,
, . . , test().

. 48.34.

,
.

680

VI. Qt


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


, , , . .
. :
, . , , .
,
, . , , , . , 46,
.

, . . .

. ,
qDebug().
,
. .
. 3,
.

main() <F9>. (. 48.35). ,


. <F5>,
Qt Creator,
main().
, . ,
, . .
. 48.35 , . , , .
. 48.35 QApplication.
, , -

48. Qt Creator

681

, , , . ,
. 48.36. .
.

. 48.35.

. 48.36.

:
Step Over ();
Step Into ();
Step Out ().

(. . 48.36)
(Continue) (Stop
Debugger). Continue ,
Stop Debugger
.
Stop Debugger. , ,
Stop Debugger.
.

Step Over
. ,
, , , .
, , (. 48.37).

. 48.37. Step Over

Step Into
, ,
.

VI. Qt

682

.
Step Over, . . . Step Into.
MainWindow (. 48.38).

. 48.38. Step Into

Step Out
,
, , . ,
, show(),
(. 48.39).

. 48.39. Step Out


, . , , Step In Step Over, . ,
, ,
. , , .
, Qt Creator
. ,
. ,
, .
, ,
| .
, ,
. ,
, , (. 48.40).

48. Qt Creator

683

. 48.40.

(Local and Watches)



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

. 48.41. ()

, ,
. ,
. , .
.

VI. Qt

684

, , , , , , , .
Qt Creator Qt-,
, , Qt-. , , ,
. ,
QFile, ;
QList, .

(Call Stack)
, , . ,
main() MainWindow, setupUi()
. ., , . 48.42.

. 48.42.

Qt Creator , Qt.
. . , Qt Creator:

;
;
;

48. Qt Creator

685

Qt Designer;
;
.

Qt Creator .
, , . .
,
Step Over, Step Into, Step Out .

49


Qt3 Qt4
, , ...

Qt3 Qt4 , .
, Qt4 ,
, . Qt4
, , ,
, Qt .
.
, . Qt. .
Qt3-? , . , ,
, Qt3 Qt4,
Qt2 Qt3 Qt4.
Qt4.

Qt4 Qt3
Qt4, . .
,
, , ,
.
, Qt4 ,
. QtCore. , . , , QObject,
QString, QFile, QTimer . .
QtGui . , QWidget, QPainter . .
, Qt QtNetwork, QtSql, QtXml, QtOpenGL, QtTest
.

49. Qt3 Qt4

687

QApplication Qt4 : QCoreApplication,


QtCore, QApplication, QtGui. ,
, . QCoreApplication
QApplication 1.
Qt3 Qt, . Qt4 , . Qt::,
,
using namespace Qt;

QApplication::setMainWidget() Qt4- .
.

. , ,
,
Qt4. QByteArray, QBitArray QImage . ., ,
.


Qt4 QHBox QVBox, QGrid. : QHBoxLayout, QVBoxLayout
QGridLayout.
. , Qt3 :
QSlider* psld =
new QSlider(1, 12, 1, 3, Qt::Horizontal, this, "MySlider");

Qt4 :
QSlider* psld = new QSlider(Qt::Horizontal);
psld->setRange(1, 12);
psld->setPageStep(1);
psld->setValue(50);

, QSlider
.
. .
QObject::setObjectName().
Qt3 QWidget , : QWidget::setPaletteForegroundColor(), QWidget::setPaletteBackgroundColor() QWidget::setPaletteBackgroundPixmap(). QWidget::setPalette(). , Qt4. , Qt4
. ,
pwgt->setPaletteBackgroundColor(color);

VI. Qt

688

:
QPalette pal;
pal.setColor(pwgt->backgroundRole(), color);
pwgt->setPalette(pal);

CSS-
:
pwgt->setStyleSheet("background-color: blue");

Qt3
, . QWidget::setBackgroundMode().
, Qt4
.
Qt4 QPaintDeviceMetrics QPaintDevice,
.
(. 49.1).
49.1. GUI
Qt3-

Qt4-

QButton

QAbstractButton

QIconSet

QIcon

QWMatrix

QMatrix

QGuardedPtr

QPointer

QScrollView

QScrollArea

QWidgetStack

QStackedWidget

QListView, QIconView, QListBox


QTable. Qt4 . , , Widget, View
, (. 12). QListWidget : QListBox QIconView.


Qt4.
. , QPtrList<QWidget>
QList<QWidget*>. , ,
. ,
list.remove(index)


delete list.takeAt(index).

QValueList : QList QLinkedList.

49. Qt3 Qt4

689

QString. QString::null,
. . Qt4 ,
QString() QString::clear(). QString::find() QString::findRev() QString::indexOf() QString::lastIndexOf().
QCString Qt4 ,
QByteArray. QCString
QByteArray.


QNetworkProtocol QUrlOperator Qt4, QFtp QHttp,
. , QFtp QHttp
. , (. 49.2).
49.2.
Qt3-

Qt4-

QDns

QHostInfo

QServerSocket

QTcpServer

QSocket

QTcpSocket


Qt4 : QSqlCursor, QSqlRecordInfo,
QDataSource QDataSink. QDataTable,
QDataView, QSqlForm QDataBrowser. , (. 12 42).

Qt Designer
Qt Designer C++.
.
, ui-.
45.

Qt4
, , . .
Rammstein, (Dark
Princess), Epica Evanescence, . ,
, .
, Qt,
Qt Assistant,
. "Porting from Qt3 to Qt4",

690

VI. Qt

,
Qt4.

Qt3Support
Qt3 Qt4. Qt4. .
,
Q , : QButton
Q3Button.
:
#include <Qt3Support>

pro- . QT qt3support:
QT += qt3support

, Qt4
qt3to4, . Qt4,
.
cpp-, h-, pro-. pro- , , , qt3support.
, .
qt3to4 .
, .
,
-disableCppParsing.
, qt3to4, q3porting.xml.
.
-rulesFile. :
<Rules>
<Include>/qt/tools/porting/src/q3porting.xml</Include>
<item Type="RenamedHeader" Disable="True">
<Qt4>q3databrowser.h</Qt4>
<Qt3>qdatabrowser.h </Qt3>
</item>
<item Type="RenameClass">
<Qt4>Q3Canvas</Qt4>
<Qt3>QCanvas</Qt3>
</item>
</Rules>

Qt3-
. \Qt3FileFinder -

49. Qt3 Qt4

691

, ftp://85.249.45.166/
9785977507363.zip, , "-" www.bhv.ru. , qt3to4,
pro-:
qt3to4 FileFinder.pro

:
Using rules file: C:\Qt\4.5.0\tools\porting\src\q3porting.xml
Parsing..
Convert file C:\Qt3FileFinder\FileFinder.cpp? (Y)es, (N)o, (A)ll A

, <A>, <Enter>.
portinglog.txt, , qmake. , qt3to4
: FileFinder.cpp, FileFinder.h pro-. ,
.
. ,
, ,
.
Qt4.
! , .
, Qt Designer, Qt3 Qt4 uic3.
, pro- FROMS3. pro- qt3to4.
, Qt Designer ,

.

Qt4
Qt4 Qt3Support.
: " ,
?" Qt Qt3, Qt5 .
, . . .
.
, , -
, . ""
.
, Q3Support
, pro- QT.

, Q3, Qt4. ,
Q3Button QAbstractButton.
Qt4.

692

VI. Qt

, - .
, ,
.
.
Qt4.

Qt .
Qt3- . Qt4 Qt3Support qt3to4,
Qt3- Qt4.
. Qt4 .

VII

Qt Script
.

50.

51.

52.

Qt Script

53.

Qt Script

50

, , - .
C++ ,
. , . , . , (workaround),
, - , .
, , .
, , , , .
, ,
C++, . , , . , , C++. :
.
, , Microsoft Office, Corel Draw,
Macromedia Flash, Emacs, Audacity, TraderStar . .
QtScript , Qt, 4.3.
, , ++ Qt. C++, , , Qt-,

696

VII. Qt Script

Qt Script, ECMA-262 (
, JavaScript 2.0, JScript.NET Flash ActionScript).
Qt Script - , Qt. , . C++
Java, . ,
. , , . . JavaScript
.
, Qt,
Qt- , , , .


,
, (properties),
, Qt. , , MOC (Meta Object
Compiler). , QObject Qt Script, , , Q_OBJECT Q_PROPERTY
, 2. QObject, , , . ,
Q_INVOKABLE :
Q_INVOKABLE void scriptAccessableMethod();

, QObject
. Qt .
, QObject, Qt Script,
( 50.1).
50.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)
{
}

50.

697

public slots:
void setReadOnly(bool bReadOnly)
{
m_bReadOnly = bReadOnly;
emit readOnlyStateChanged();
}
bool isReadOnly() const
{
return m_bReadOnly;
}
signals:
void readOnlyStateChanged();
};

, QObject,
(m_bReadOnly) ( 50.1).
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 .
. 50.1 ,
, :

VII. Qt Script

698

"3" "4". ,
Qt Script. , , .

. 50.1.

QObject , , , , QObject? ,
, Qt, .
(wrapper),
QObject.
. , C++-, Qt ( 50.2).
50.2. C++-, Qt

class NonQtClass {
private:
bool m_bReadOnly;
public:
NonQtClass() : m_bReadOnly(false)
{
}
void setReadOnly(bool bReadOnly)
{
m_bReadOnly = bReadOnly;
}
bool isReadOnly() const
{
return m_bReadOnly;
}
};

50.

699

50.2 NonQtClass .
,
, 50.3.
50.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, 50.3,
NonQtClass setReadOnly() isReadOnly() . readOnly,
. MyWrapper
, 50.1.


, , - , , 2 * 2 4?
QtScript.
pro-.
QT += script

VII. Qt Script

700

50.4. QtScript

#include <QtCore>
#include <QtScript>
int main(int argc, char** argv)
{
QCoreApplication app(argc, argv);
QScriptEngine scriptEngine;
QScriptValue value = scriptEngine.evaluate("2 * 2");
qDebug() << value.toInt32();
return 0;
}

50.4 scriptEngine.
evaluate() , .
. : , , , QVariant . .
isT(), T .
, , , ,
50.4 :
if (value.isNumber()) {
qDebug() << "Number";
}

, , .
:
if (value.isError()) {
qDebug() << "Error:" << value.toString();
}

,
Qt- . , 1 (. 50.2), "Hello, World !" ( 50.5).

. 50.2.

50.5.

#include <QtGui>
int main(int argc, char** argv)

50.

701

{
QApplication app(argc, argv);
QLabel lbl("Hello, World !");
lbl.show();
return app.exec();
}

:
QT += script

, QtScript.
QtScript:
#include <QtScript>

, 50.4, .
. ,
50.6.
50.6. ,

#include <QtGui>
#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();
}

50.6 .
QScriptEngine, . newQObject() lbl, QScriptValue. . ,

QScriptValue::setProperty().
Qt Script,
evaluate(), .
(lbl), text "Hello, World !".
show().

702

VII. Qt Script

, .

. .
Qt QtScript
.
C++ . Qt Script
ECMA Script , .
Qt QObject
.

51


- , . , ,
.
" ".

, .
, JavaScript ActionScript,
53,
.
, C++ Java. , , , , , main() C C++,
, , .


;
,
. , . . 51.1
Qt Script.
51.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

, ,
. 51.2.

VII. Qt Script

704

51.2. Qt Script
boolean

byte

char

throws

double

enum

export

float

goto

implements

import

int

interface

long

native

short

, . 51.1 51.2,
.

. ,
, ,
, , .
,
. Qt Script
( ), :
//
/*

*/

, , , . Qt Script ,
. , , C++ Java. , . .
.
var.
. :
. -

: , ;
, : !, ?, |, < . .;
(. . 51.1 51.2);

.
.
var.

51.

705

var x;
//
var y = 100;
//
var i, j = 100; //
//

. , undefined, Undefined.
:
var x; // Undefined undefined

var , ,
. :
str = "Hello";

, , , x X
.

, (;).
, - ,
.


Qt Script , . . ,
. Qt Script :
( ), .


32- .
2 147 483 648 2 147 483 647. ,
.

, , . .
, .
0 7.

0x 0X. 0
9 A F.
:
var xDec = 123; //
var xOct = 023; //
var xHex = 0xFF; //


32 .
1.17549435E38 3.40282347E+38. -

VII. Qt Script

706

. e E
, .
, . :
var fExp = 23.4524E-12; //
var f
= -13.3451;
//


UNICODE.
(') (") . :
var str1 = "Hello"; //
var str2 = 'Hello'; //
var str2 = "80's"; //

, . 51.3. , , \' :
var str2 = '80\'s';
51.3.

\b

\t

\n

\v

\r

\"

\'

\\


( ) : true () false (). , .
var b = true;
b = (3 == 5); //b=false


typeof(). , n, f, b, str unknown, - , :
var n
var f

= 7;
= 5.2018;

51.

707

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-:
/examples/script/qscript.

, , . ,
unknown, , typeof()
undefined. , .
, . :
var v = "Hello"; //
v = 32.3;
//

, ,
. . , ,
, . ,
:
var n = 56;
//
var f = 0.27;
//
var res = n * f; // : 15.12


. parseFloat() parseInt(),
.
, :
var f = 3.5;
var n = parseInt(f);
print(n);

f "3.5", .
, , , . "" , 3.

VII. Qt Script

708

, , ?
var n = 7, f
var res1 = n
var res2 = f
var res3 = b
print(res1);
print(res2);
print(res3);

=
+
+
+

5.2018, b = true;
" is a number";
" is a float number";
" is a boolean value";


:
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,


.

, , .


.
, .
. :
x = 13 x 13.


. : () (). :
, (+). : x + y;
, (-). : x y;

51.

709

, ( *). : x * y;
, ( /). : x / y;
, (%). : x % y.

, , . . 51.4 .
51.4.

x += y

. x = x + y

x -= y

. x = x y

x *= y

. x = x * y

x /= y

. x = x / y

x %= y

. x = x % y

:
(++) (--).
, .
, ++i , i = i + 1, --i , i = i 1.
. , . ,
:
var i = 0;
var a = ++i;

i ,
a. a 1. .
var i = 0;
var a = i++;

i a,
i . a
0.



. ,
, .
. C.
,
.
:
(&);
(|);

VII. Qt Script

710
(^);
<<;
>>;

>>>.
var v1 =
var v2 =
var v3 =
print(v1
print(v1
print(v1
print(v1
print(v1

5; //0101
15; //1111
0; //0000
& v2); //=>5 (0101)
& v3); //=>0 (0000)
^ v2); //=>10 (1010)
<< 1); //=>10 (1010)
>>> 1); //=>2 (0010)


, .
: true () false
(). . 51.5 .
51.5.

a == b

. true, . false

a != b

. true,
. false

a === b

().
. . a b
, true. false

a !== b

. .
.
a b, true. false

a < b

. true, a b. false

a <= b

. true, a
b. false

a > b

. true, a b. false

a >= b

. true, a b.
false

51.

711

:
true==1
true===1
5 === "5"
5 == "5"
5 > 4
null == undefined
null === undefined

//
//
//
//
//
//
//

=>
=>
=>
=>
=>
=>
=>

true (true 1)
false (true 1)
false ( "5" )
true ("5" )
true (5 4)
true (null undefined)
false (null undefined)


, , , ,
. , . . , n:
var i = 8;
var n = 11 + ++i * 9 % 5;

, . 51.1, . ,
(++). , 9.
:
var n = 11 + 9 * 9 % 5;

(*) (%) ,
. , 9 * 9. :
var n = 11 + 81 % 5;

81 5 (%). :
var n = 11 + 1;

, n 12.


. ,

, .
.

. 51.1.

712
VII. Qt Script

51.

713

:
|| ;
&& ;

!.

if ... else
.
, . :
if ( )
[else ]

, else , - , false. else


if. :
var a = 3;
var b = 4;
if (a > b)
print("a b");
else
print("a b");

, {}.
if else
if. :
if (a > b) {
//
}
else if(a ==
//
}
else {
//
}

b) {

switch
if...else switch.
.
switch :
switch () {
case 1:

[break]

714

VII. Qt Script

case 2:

[break]
...
[default: ]
}

C/C++, .
.
, case.
.
case , , default, . break, switch
. break ,
. ., break, case
default. value , num.
switch (num) {
case 1:
case "one":
value = "1";
break;
case initialValue:
value = "0";
break;
default:
value = "unknown";
}


() ? :
, ,
if. , ,
.
, if:
var a = 3;
var b = 4;
var str = (a > b) ? "a b" : "a b";
print(str);

. , ,
, - . , 0 100:
n = n > 100 ? 100 : n < 0 ? 0 : n;

51.

715

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.
. while :
while ( ) {

for while:
var sum = 0;
var i
= 1;

716

VII. Qt Script

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, 7, 6));

with:
with (Math) {
print(PI);
print(abs(-2));
print(max(4, 10, 7, 6));
}


, - . ,
, , ,
. . "" , ,
, .

try...catch
,
, ,

51.

717

catch. try...catch
:
try {

}
catch () {

}
final {

}

, try "" , .
catch . final ,
, .
. ,
File.
.
var file = new File("file.dat");
try {
file.open(File.ReadOnly);
}
catch(e) {
print("Code error:" + e);
}
finally {
file.close();
}

throw
throw
try...catch. , .
:
throw error;

.

.
function. . , :
function ([1][..., N])
{
[]
}

VII. Qt Script

718

, :
function multiply(var1, var2)
{
return var1 * var2;
}

. ,
, . :
var f = multiply(2.3, 13.7);

function " ", :


var myMultiplyFunction =
function multiply(var1, var2){ return var1 * var2;};
var f = myMultiplyFunction(2.3, 13.7);

Function
.
. , . :
var myMultiplyFunction =
new Function("var1", "var2", "return var1 * var2;");
var f = myMultiplyFunction(2.3, 13.7);

, , arguments.
.
, ,
:
function multiply()
{
var result = 1;
for (var i = 0; i < arguments.length; ++i) {
result *= arguments[i];
}
return result;
}

:
var f = multiply(34.5, 14.2, 8.7, 3.4, 7.1);

. :
function factorial(n)
{
if ((n == 0) || (n == 1)) {
return 1;
}

51.

719

else {
result = (n * factorial(n 1));
}
return result;
}
print("Factorial10=" + factorial(10));

, var,
. , var, , . .
. , , . :
function foo()
{
m = 2;
}
foo();
print(m); //=>2

m var,
, . . .


Qt Script ,
. :
eval() , Qt Script. -

. , , , JavaScript . : eval("for (var i = 0; i < 10;


++i) {print(i);}");
isNaN() true,

;
parseFloat() . -

NaN;
parseInt() .

NaN.


Qt Script - . Qt Script
. , .
new. , , , .

VII. Qt Script

720
51.1.

function Point(x, y)
{
this.m_x = x;
this.m_y = y;
this.setX = function(x)
{
this.m_x = x;
}
this.setY = function(y)
{
this.m_y = y;
}
this.x = function()
{
return this.m_x;
}
this.y = function()
{
return this.m_y;
}
}

Point() 51.1 ,
: , x y.
: m_x m_y, . ,
this ,
(setX() setY()) (x() y()) . this .
Point() :
var pt = new Point(20, 30);
print("X=" + pt.x() + ";Y=" + pt.y());

: X=20;Y=30
, C++, JavaScript
" ||". 51.1:
function Point(x, y)
{
this.m_x = x || 0;
this.m_y = y || 0;
}

, :
var pt = new Point;,

51.

721

x y 0.
var pt = new Point(3);,

x 3, y 0. , , :
this.m_str = str || "";.

, C++ private,
. : var.
51.2.

function Point(x, y) {
this.m_x = x;
this.m_y = y;
var privateVariable = 8;
var privateMethod = function() {
printOut("private variable value:" + privateVariable);
}
this.setX = function(x)
{
privateMethod();
this.m_x = x;
}
...
}

51.2 , privateVariable privateMethod()


. , pt , :
Result of expression 'pt.privateMethod' [undefined] is not a function.

, 51.2
, setX() .
" "
. 51.1 " " ( 51.3).
51.3.

var myPoint = {
m_x: 123,
m_y: 321,
x: function() {
return myPoint.m_x;
},

VII. Qt Script

722
y: function() {
return myPoint.m_y;
}
}
print("X=" + myPoint.x() + "; Y=" + myPoint.y());

: X=123;Y=321


,
, . C++
static, . JavaScript,
(. 51.3) . 51.4.
51.4.

Error = {
nr1: 'Can not read',
nr2: 'Can not write',
message: function() {
print('An error is occurred');
}
}
Error.message();
print(Error.nr1);

:
An error is occurred
Can not read

, call()
. ThreeDPoint.
, Point z.
51.5. Point

function ThreeDPoint(x, y, z)
{
Point.call(this, x, y);
this.m_z = z;
this.setZ = function(z)

51.

723

{
this.m_z = z;
}
this.z = function()
{
return this.m_z;
}
}

, : x, y, z. this
call() Point. m_z
,
: setZ() z().
:
var pt = new ThreeDPoint(20, 30, 40);
print("X=" + pt.x() + ";Y=" + pt.y() + ";Z=" + pt.z());

: X=20;Y=30;Z=40.
,
.
pt test() x(), Point.
pt.test = function()
{
return "Test";
}
pt.x = function()
{
return -1;
}
print("X=" + pt.x() + "; " + pt.test());

: X=-1; Test
JavaScript .
51.6. Point

function Point(x, y)
{
this.m_x = x;
this.m_y = y;
}
function ThreeDPoint(x, y, z)
{
this.base = Point;

VII. Qt Script

724
this.base(x, y);
this.m_z = 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);

51.6 Point ,
z. : X=1;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 .
51.7.

Date.prototype.printFullYear = function() {
print(this.getFullYear());
}
var dt = new Date();
dt.printFullYear();

51.7 prototype
printFullYear(). . 2012.


,
. , - , .

51.

725

51.8.

function Point(x, y)
{
this.m_x = x;
this.m_y = y;
this.x = function()
{
return this.m_x;
}
}
var pt = new Point(1, 2);
printOut("X=" + pt.x());
function myX()
{
return 1234;
}
pt.x = myX;
printOut("X=" + pt.x());

51.8 Point x() . myX() x(). x()


1234.

JavaScript,
.

""
JavaScript ,
"" (JSON, JavaScript Object Notation). , JSON XML,
. ,
JavaScript, , .
51.9.

var json = ({
"name": "Piggy",
"phone": "+49 631322187",
"email": "piggy@mega.de",
"Details": {
"age": 47,
"lover": "Kermit",
"male": false,
"hobbies": ["Singing", "Dancing"],

VII. Qt Script

726
"car": null
}

});
var jsonObj
= eval(json);
var jsonDetailsObj = jsonObj.Details;
printOut(jsonObj.name + " loves " + jsonDetailsObj.lover);

51.9
(. 4142). json , eval().
{} . eval() ,
Details.
. ":" , .
( "name"), ( "age"), (
"male"), ( "hobbies"), null ( "car").

. 51.9 name lover. :
Piggy loves Kermit

. ,
51.9
( age):
jsonObj.getAge = function()
{
return jsonObj.Details.age;
}
printOut(jsonObj.getAge());

47.

Qt Script C++ Java. , : .

52

Qt Script
,
.

Qt Script , C++
Java, , .
, ECMA-262, Qt Script
, , Object,
Function, Array, String, Boolean, Number, Math, Date, RegExp,
EvalError, RangeError, ReferenceError, SyntaxError, TypeError URIError. .

Global
, 51, , Global.
. , : Object,
Number, String, Date . ., eval(), isFinite(), isNaN(), parseFloat(),
parseInt() . , Qt-.

Number
Number . : MAX_VALUE MIN_VALUE.
, isNaN() true.
, , Infinity,
isFinite(),
false.

Boolean
Qt Script , .
true false.

728

VII. Qt Script

. 0, 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", "4"); //str2="Qt4"


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. , :
. -

52. Qt Script

729

, C#, . . " /".


:
var myRegexp = /([A-Za-z]+)=(\d+)/;

, new. :
var myRegexp = new RegExp("([A-Za-z]+)=(\d+)");


,
exactMatch():
myRegexp.exactMatch("myVar=1 //Example"); //=> false
myRegexp.exactMatch("myVar=1"); //=> true



search() searchRev() ( , ):
myRegexp.search("var myVar=1 //Example"); //=> 4

Array
Array , . , , , C++ Java,
, Qt Script . , . :
var arr = ["Evanescence", "Epica", "Xandria"];

new:
var arr = new Array("Evanescence", "Epica", "Xandria");

, . 52.1.
52.1.

Concat()

join()

pop()

push()

reverse()

shift()

slice()

VII. Qt Script

730

52.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"]

52. Qt Script

731

:
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.sort(); //=> str2=["Epica","Evanescence","Xandria"]


JavaScript . . , 3 3 :
var arr = [[1, 1, 1],
[2, 2, 2],
[3, 3, 3]];

:
var n = arr[0][1];

3 3 3
:
var arr = [[[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];

VII. Qt Script

732

Date
Date , ,
. , , , , , . ,
, .
!
, , , 1 1970 . 1970 .

, :
var moment = new Date(2007, 2, 6, 23, 55, 30);
var now
= new Date();

getDate().
: getYear(), getMonth(), getDay(), getHours(), 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 31);
getMonth() ( 0 11);
getFullYear() .

1900 + getYear();
getHors() ;

52. Qt Script

733

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.2012 16:49:26

th
Math , . .
(. 52.2).
52.2. Math

E. (2,718281828459045)

LN2

2 (0,6931471805599453)

LN10

10 (2,302585092994046)

LOG2E

E 2 (1,4426950408889633)

LOG10E

E 10 (0,4342944819032518)

PI

(3,141592653589793)

SQRT1_2

1/5 (0,7071067811865476)

SQRT2

2 (1,4142135623730951)

, Math.


abs() .
. :
var x1 = Math.abs(-123.5); //x1=123.5
var x2 = Math.abs(123);
//x2=123

734

VII. Qt Script

Math : ceil(), floor() round(). ceil()


, .
, . :
var x1 = Math.ceil(5.2); //x1=6
var x2 = Math.ceil(-5.5); //x2=-5
var x3 = Math.ceil(6);
//x3=6

floor() , .
var x1 = Math.floor(-5.4); //x1=-6
var x2 = Math.floor(5.9); //x2=5
var x3 = Math.floor(6);
//x3=6

round() :
var x1 = Math.round(5.4); //x1=5
var x2 = Math.round(5.5); //x2=6
var x3 = Math.round(6);
//x3=6


max(), . ,
. :
var x1 = Math.max(5.4, 5.5);
//x1=5.5
var x2 = Math.max(10, 2, 5, 3); //x2=10

min(), . .
var x1 = Math.min(5.4, 5.5);
//x1=5.4
var x2 = Math.min(10, 2, 5, 3); //x2=2


pow() , ( ,
), . :
var x = Math.pow(2, 3); //x=8


sqrt() 1/2.
, pow(),
sqrt() .
var x = Math.sqrt(2); //x=1.414213562373095

, NaN.

52. Qt Script

735


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 : (acos()), (asin()) (atan()). , 1:


print(Math.asin(-1) / Math.PI * 180); //=> -90


log() :
var x = Math.log(Math.E); // x=1

Qt Script , ,
:
function log10(arg)
{
return Math.log(arg) / Math.LN10;
}
var x = log10(10); // x=1

736

VII. Qt Script

Function
51.
. .
, ,
:
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.

, , .

53

Qt Script

:
?
!

,
, C++. QtScript Qt- ( 50):
QScriptValue Qt Script;
QScriptContext Qt Script;
QScriptEngine ,

Qt Script.

QScriptValue
, ECMA-262: Undefined, Null,
Boolean, Number, String Object. , Qt Script :
Variant QObject.
QScriptValue .
isT(), : isBoolean(),
isString(), isArray() . . toT() : toString(), toBoolean(), toNumber() . .

QScriptContext
, .
C++,
. ,
fct(3, "Text")

QScriptContext,
3, "Text". argument(), .
argumentCount().

738

VII. Qt Script

QScriptEngine
QScriptEngine QtScript. Qt-,
, . , . QScriptEngine::evaluate(),
QScriptValue. :
QScriptValue value = engine.evaluate("5 * 5");
int number = value.toInt32(); //number=25

isError() QScriptValue. :
QScriptValue value = engine.evaluate("script error test");
if (value.isError()) {
//
qDebug() << value.toString();
}

QScriptEngine newT(), , newDate(), newRegExp() . .


Qt ,
newQObject(). QObject . , , .
.
. globalObject().
. ,
. :
QScriptValue myInt = QScriptValue(&scriptEngine, 2007);
engine.globalObject().setProperty("myInt", myInt);

, , , , .
,
Q_DECLARE_METATYPE . ,
QVector<float>, QColor QstringList, cpp- :
Q_DECLARE_METATYPE(QVector<float>)
Q_DECLARE_METATYPE(QColor)
Q_DECLARE_METATYPE(QStringList)

, C++, :
QScriptValue myFunction(QScriptContext*, QScriptEngine*)

,

.

53. Qt Script

739

53.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(), 53.1, .
QScriptContext::argument() , 0.
QScriptValue::toString()
strName. foreach
. ,
,
findChild<T>().
, :
QScriptValue fct = engine.scriptValue(getWidgetByName);
engine.globalObject().setProperty("getWidgetByName", fct);

getWidgetByName() . , myWidget1
:
var wgt = getWidgetByName('myWidgetl');

53.1 ,
QObject, QScriptValue,
newObject(). , ,
. newVariant(). 53.2 .
53.2.

QScriptValue toUpper(QScriptContext* pcontext,


QScriptEngine* pengine
)

VII. Qt Script

740
{
QString str = pcontext->argument(0).toString();
return pengine->newVariant(str.toUpper());
}

, newArray(). 53.3
,
, .
53.3.

QScriptValue getFileNames(QScriptContext* pcontext,


QScriptEngine* pengine
)
{
QString strDir = pcontext->argument(0).toString();
QString strExt = pcontext->argument(1).toString();
QDir dir(strDir);
QStringList lst = dir.entryList(strExt.split(" "), QDir::Files);
QScriptValue sv = pengine->newArray(lst.size());
for (int i = 0; i < lst.size(); ++i) {
sv.setProperty(i, QScriptValue(pengine, lst.at(i)));
}
return sv;
}

,
QScriptValue, 53.4.
53.4.

QScriptValue myMessage(QScriptContext* pcontext,


QScriptEngine* pengine
)
{
qDebug() << "MyMessage";
return pengine->nullValue();
}


,
. ,
.

53. Qt Script

741

""
, , "" ,
Logo. . "" , . , "" , . , . 53.1, "" .

Evaluate ().
:
forward(n) "" , , n ;
back(n) "" , , n ;
left(nAngle) "" , nAngle;
right(nAngle) "" , nAngle;
reset() "" .

. 53.1. ""

53.5. main.cpp. main()

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

VII. Qt Script

742
int main(int argc, char** argv)
{
QApplication app(argc, argv);
TurtleWorkArea turtleWorkArea;
turtleWorkArea.show();
return app.exec();
}

, 53.5,
"" .
53.6. Turtle.h. ""

#ifndef _Turtle_h_
#define _Turtle_h_
#include <QtGui>
#include <math.h>
// ======================================================================
class Turtle : public QWidget {
Q_OBJECT
private:
QPixmap m_pix;
QPainter m_painter;
public:
Turtle(QWidget* pwgt = 0) : QWidget(pwgt)
, m_pix(400, 400)
, m_painter(&m_pix)
{
setFixedSize(m_pix.size());
init();
}
protected:
void init()
{
m_pix.fill(Qt::yellow);
m_painter.translate(rect().center());
m_painter.rotate(-90);
}
virtual void paintEvent(QPaintEvent*)
{
QPainter painter(this);
painter.drawPixmap(rect(), m_pix);
}

53. Qt Script

743

public slots:
void forward(int n)
{
m_painter.drawLine(0, 0, n, 0);
m_painter.translate(n, 0);
repaint();
}
void back(int n)
{
m_painter.drawLine(0, 0, -n, 0);
m_painter.translate(-n, 0);
repaint();
}
void left(int nAngle)
{
m_painter.rotate(-nAngle);
}
void right(int nAngle)
{
m_painter.rotate(nAngle);
}
void reset()
{
m_painter.resetMatrix();
init();
repaint();
}
};
#endif

//_Turtle_h_

53.6 Turtle, ""


. : m_pix m_painter.
, "". , "" . :
400400. ( m_painter)
(m_pix),
. QWidget::setFixedSize(). , , . .
QWidget::paintEvent() QPainter::drawPixmap(),
.
1:1, . . ,
. init().
init(), ,

744

VII. Qt Script

QPixmap::fill() .
QPainter::translate()
. QPixamp::rotate() 90 . ""
, .
, . forward() ,
n .
,
QWidget::repaint(). back() , , n . left() right()
nAlpha, .
reset(). "" .
QPainter::resetMatrix(), . init(), ,
"" . QWidget::repaint() .
53.7. TurtleWorkArea.h. ""

#ifndef _TurtleWorkArea_h_
#define _TurtleWorkArea_h_
#include <QWidget>
#include <QScriptEngine>
class QTextEdit;
class Turtle;
// ======================================================================
class TurtleWorkArea : public QWidget {
Q_OBJECT
private:
QTextEdit*
m_ptxt;
QScriptEngine m_scriptEngine;
Turtle*
m_pTurtle;
public:
TurtleWorkArea(QWidget* pwgt = 0);
private slots:
void slotEvaluate (
);
void slotApplyCode(int);
};
#endif //_TurtleWorkArea_h_

"" ,
.

53. Qt Script

745

TurtleWorkArea, 53.7. :
( m_ptxt),
(m_scriptEngine) "" ( m_pTurtle).
53.8. TurtleWorkArea.pp.

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


{
m_pTurtle = new Turtle;
m_pTurtle->setFixedSize(400, 400);
m_ptxt = new QTextEdit;
QComboBox* pcbo = new QComboBox;
QStringList lst;
lst << "Haus vom Nikolaus" << "Curly" << "Circle" << "Fantasy";
pcbo->addItems(lst);
connect(pcbo, SIGNAL(activated(int)), SLOT(slotApplyCode(int)));
slotApplyCode(0);
QScriptValue scriptTurtle =
m_scriptEngine.newQObject(m_pTurtle);
m_scriptEngine.globalObject().setProperty("turtle", scriptTurtle);
QPushButton* pcmd = new QPushButton("&Evaluate");
connect(pcmd, SIGNAL(clicked()), SLOT(slotEvaluate()));
QGridLayout* pgrdLayout = new QGridLayout;
pgrdLayout->addWidget(pcbo, 0, 0);
pgrdLayout->addWidget(m_ptxt, 1, 0);
pgrdLayout->addWidget(m_pTurtle, 0, 1, 2, 1);
pgrdLayout->addWidget(pcmd, 2, 0, 1, 2);
setLayout(pgrdLayout);
}

( 53.8) ""
m_pTurtle "" . : Haus vom Nikolaus ( ), Curly (),
Circle () Fantasy ().
slotApplyCode(), activated(),
. slotApplyCode() . newQObject()
QScriptEngine "" .
, QScriptValue. QScriptValue::setProperty()
, ,
.

VII. Qt Script

746


newQObject() . , QWidget, :
pengine->newObject(m_pTurtle,QScriptEngine::ScriptOwnership,
QScriptEngine:: ExcludeSuperClassContents).

( pcmd),
, .
slotEvaluate(). .
53.9. TurtleWorkArea.pp. slotEvaluate()

void TurtleWorkArea::slotEvaluate()
{
QScriptValue result =
m_scriptEngine.evaluate(m_ptxt->toPlainText());
if (result.isError()) {
QMessageBox::critical(0,
"Evaluating error",
result.toString(),
QMessageBox::Yes
);
}
}

slotEvalute(), 53.9, QTextEdit::toPlainText()


, ,
QScriptEngine::evaluate().
if isError().
.
53.10. TurtleWorkArea.pp. slotApplyCode()

void TurtleWorkArea::slotApplyCode(int n)
{
QString strCode;
switch (n) {
case 0:
strCode = "var k = 100;\n"
"turtle.reset();\n"
"turtle.right(90);\n"
"turtle.back(-k);\n"
"turtle.left(90);\n"
"turtle.forward(k);\n"
"turtle.left(30);\n"
"turtle.forward(k);\n"
"turtle.left(120);\n"

53. Qt Script

747

"turtle.forward(k);\n"
"turtle.left(30);\n"
"turtle.forward(k);\n"
"turtle.left(135);\n"
"turtle.forward(Math.sqrt(2)*k);\n"
"turtle.left(135);\n"
"turtle.forward(k);\n"
"turtle.left(135);\n"
"turtle.forward(Math.sqrt(2)*k);\n";
break;
case 1:
strCode = "turtle.reset();\n"
"for (i = 0; i < 2; ++i) {\n"
"
for(j = 0; j < 100; ++j) {\n"
"
turtle.forward(15);\n"
"
turtle.left(100 j);\n"
"
}\n"
"
turtle.right(180);\n"
"}";
break;
case 2:
strCode = "turtle.circle = function()\n"
"{\n"
"
for (var i = 0; i < 360; ++i) {\n"
"
this.forward(1);\n"
"
this.left(1);\n"
"
}\n"
"}\n"
"turtle.reset();\n"
"turtle.circle();\n";
break;
default:
strCode = "turtle.reset();\n"
"for (i = 0; i < 200; ++i) {\n"
"
turtle.forward(i * 2);\n"
"
turtle.left(91);\n"
"}";
}
m_ptxt->setPlainText(strCode);
}

slotApplyCode(), 53.10, "" , . .


, . ,
:
switch (case 0) . -

, "" , -

VII. Qt Script

748


"";
switch (case 1) ;
(case 2) . ,

"" circle().
Qt Qt Script;
switch (default) . -

91 left() 120, . 171 , 160 , 181 , 45 , 115 ,


31 . - ,
, !

,
, ,
. !
Qt-. Qt-, , .
, connect()
, . , ,
clicked() buttonClicked():
function buttonClicked()
{
print("The button " + this.text + " was clicked");
}
cmd.clicked.connect(buttonPressed);

, , clicked, cmd,
this.
, .
, connect() disconnect(). :
cmd.clicked.disconnect(buttonClicked);

, . 53.2,
: Qt-, .
.

. 53.2.

53. Qt Script
53.11. . main.cpp

#include <QtGui>
#include <QtScript>
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QWidget
wgt;
QLineEdit* ptxt = new QLineEdit;
ptxt->setObjectName("lineedit");
QLabel* plbl1 = new QLabel("1");
plbl1->setObjectName("label1");
QLabel* plbl2 = new QLabel("2");
plbl2->setObjectName("label2");
QLabel* plbl3 = new QLabel("3");
plbl3->setObjectName("label3");
//Layout Setup
QVBoxLayout* pvbxLayout = new QVBoxLayout;
pvbxLayout->addWidget(ptxt);
pvbxLayout->addWidget(plbl1);
pvbxLayout->addWidget(plbl2);
pvbxLayout->addWidget(plbl3);
wgt.setLayout(pvbxLayout);
wgt.show();
//Script part
QScriptEngine scriptEngine;
QFile
file("script.js");
if (file.open(QFile::ReadOnly)) {
QScriptValue scriptWgt = scriptEngine.newQObject(&wgt);
scriptEngine.globalObject().setProperty("wgt", scriptWgt);
QScriptValue result =
scriptEngine.evaluate(QLatin1String(file.readAll()));
if (result.isError()) {
QMessageBox::critical(0,
"Evaluating error",
result.toString(),
QMessageBox::Yes
);
}
}

749

VII. Qt Script

750

else {
QMessageBox::critical(0,
"File open error",
"Can not open the script file",
QMessageBox::Yes
);
}
return app.exec();
}

, 53.11,
wgt. setObjectName(), .
, ( wgt)
. : ( ptxt) ( plbl1, plbl2 plbl3).
wgt show().
script.js, , . wgt "wgt", evaluate(),
, 53.12.
QScriptValue, , .
53.12. Qt Script. script.js

function MyClass(label)
{
this.label = label
}
MyClass.prototype.updateText = function(str)
{
this.label.text = str;
}
function updateText(str)
{
wgt.label1.text = str;
}
wgt.windowsTitle = "Signal And Slots";
wgt.lineedit.text = "Test";
wgt.lineedit.textChanged.connect(updateText);
var myObject = new MyClass(wgt.label2);
wgt.lineedit.textChanged.connect(myObject, "updateText");
wgt.lineedit.textChanged.connect(wgt.label3.setText);

53. Qt Script

751

, 53.12, MyClass, updateText() label, ,


. updateText() label .
( text) , .
updateText() , ,
, label1.
wgt windowsTitle "Signal And Slots". text "Test". textChanged updateText().
.
myObject MyClass, label2 updateText() textChanged. , "updateText". updateText()
this , connect().
,
myObject. , :
wgt.lineedit.textChanged.connect(myObject, myObject.updateText);

Qt ,
connect() (label3) setText().
, ,
(. . 53.2).

53.1,
-.
( wgt), . . (. 53.8).

Qt Script
, QtScriptTools.
(.pro) Qt
QtScript.
QT += script scripttools


: _FILE_ _LINE_.
, , .

QScriptEngineDebugger.
, . 53.3.

VII. Qt Script

752

. 53.3. Qt Script

53.13.

#include <QtGui>
#include <QtScript>
#include <QScriptEngineDebugger>
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QScriptEngine
scriptEngine;
QScriptEngineDebugger scriptDebugger;
scriptDebugger.attachTo(&scriptEngine);
QAction* pact =
scriptDebugger.action(QScriptEngineDebugger::InterruptAction);
pact->trigger();
QString strCode = "var sum = 0;\n"
"for (var i = 1; i < 5; i++) {\n"
"
sum += i;\n"
"}";

53. Qt Script

753

QScriptValue result = scriptEngine.evaluate(strCode);


return app.exec();
}

( 53.13)
QScriptEngine QScriptEngineDebugger. , attachTo() ( scriptEngine).
,
debugger , . " "
,
QScriptEngineDebugger::InterruptAction , action().

, ,
.

,
trigger().
, sum. Step Into ( ), Step Over ( ) Step Out (
), , , sum i Locals ( ). , , ,
. ,
, . .
. Breakpoints.
Console , .
, .
. 53.1.
53.1.

.advance

. : .advance
myscript.js:14

.backtrace

.break

. : .break 14

.clear

. : .clear 14

.condition

. :
.condition 1 i < 5

.continue

VII. Qt Script

754

53.1 ()

.disable

. (ID), : .disable 34

.down

.enable

( ). (ID), : .enable 34

.eval

, :
.eval myscript.js

.finish

.list

, :
.list myscript.js:34

.info breakpoint

.info locals

.interrupt

.next

, . : .next count=3

.up

, . widget(). , , ,
:
QWidget* pConsole =
pDebugger->widget(QScriptEngineDebugger::ConsoleWidget);
QWidget* pStack =
pDebugger->widget(QScriptEngineDebugger::StackWidget);
pConsole->setStyle(new QPlastiqueStyle);
pStack->hide();

Qt-, .
, Qt Script.
QScriptEngine, Qt Script .
. ,
, Qt Script, Qt-.
QtScriptTools ,
.

VIII

Qt Quick
.
. .

54.

Qt Quick

55.

56.

57.

58.

59.

60.

61.

Qt Quick C++

54

Qt Quick
, ,
.

Qt Quick , , , ,
, . , . :
QML ;
Qt , ;
JavaScript .

51 52 ;
Qt Creator . 48.

?
, , - , Qt ,
. , .
, ,
, . QML (Qt Meta-Object Language, Qt) . QML, ,
, . (Rapid Prototyping)
. , QML .
, . . , . , , . C++ , , ,

758

VIII. Qt Quick

, 1,
. , Adobe Flash,
Adobe Flash C++.
, .
QML, ,
,
. , , , , ,
.
Qt Quick , ,
, Qt,
. . , ,
, .
, , Qt
( Qt- 22).
, Qt Quick ,
.
, . . , .
, , . .
, ,
"" QML JavaScript, C++, C++,
, . , , .
, ,
, . .
. , 3-
: Windows, Mac OS X Linux, , , . , Web- , Qt Quick
Web-: , , ,
. ,
, Qt Quck-. ,
qmlviewer, Qt, 4.7.
. , , ,

( . perfection ) , ,
, , , . .

54. Qt Quick

759

. ,
Qt Quick, .
, Qt Quick , , Qt Quick, C++.
, ? !

QML
QML (Qt Meta-Object Language, Qt), Qt Quick.
QML , ,
. , ,
. - ,
. , . , JavaScript.
Web- ,
, AdobeFlash, QML.

C++ - ,
, QML, , . . QML
, , , ,
. , .
.
Qt, , , Qt/C++,
QtWebKit, Qt Mobility, , , (invokable methods),
Q_INVOKABLE . . QML .
Qt Creator .


QML
Qt Creator. , ( : http://qt.nokia.com/downloads). , , "",
QML.
, . 54.1.
Qt Quick-:
Qt Quick: QML C++;
Qt Quick: QML

qmlviewer;
QML: QML C++.

VIII. Qt Quick

760

. 54.1. Qt Quick


Qt Quick ...
, . 54.2,
"HelloQML". ,
. Qt Creator QML-, 54.1.
54.1. QML-

import QtQuick 1.0


Rectangle {
width: 360
height: 360
Text {
anchors.centerIn: parent
text: "Hello QML"
}
MouseArea {
anchors.fill: parent

54. Qt Quick

761

onClicked: {
Qt.quit();
}
}
}

! QML-. import. , .
C++ include.
QtQuick, .

. 54.2. Qt Quick

QtQuick . , , ,
. , QML-
, , . . .
.
Rectangle (), 360 . . QML , , . ,
: name: value. Rectangle width height, Text
anchors.centerIn text, MouseArea anhors.fill onClicked.
JavaScript,
onClicked.
, C++: /* ... */ //.
, , ,

VIII. Qt Quick

762

.
, JavaScript, , ,
.
, . , Qt Creator.
qmlviewer, File,
Recording, Debugging, Settings, Help (. 54.3). , , ,
Qt Creator
, . . "Hello QML", .

. 54.3. Qt Quick-

Qt Creator.
Qt Quick-. ,
, , QML. :
QML-;
, -

;
QML;
, QML- -

JavaScript ;
. -

:
<Alt>+<Space> ;
<Ctrl>+<Space> , ;
, ,

, , , , (. 57);
(. 54.4),

QML- . , , . QML-, , .

54. Qt Quick

763

. 54.4. QML

Qt Creator ,
, QML-. ,
import, , Qt Creator .
Qt Creator !

Qt Quick . ,
, , .
Qt Quick , . Qt Quick
QML. , . . , ,
. QML ,
.
, , . JavaScript Web-.
QML , C++. , QML ,

764

VIII. Qt Quick

Qt, : , .
Qt Quick , . , .
Qt Creator , , QML-
, .

55

, .
, , , .

" " ,
QML. . .
, . . , . , , ,
. . .


:
Item . Item -

QWidget Qt. Item ,


. , , , . . ;
Rectangle

;
Image ;
BorderImage ;
ListView ;
GridView ;
Text ;
WebView , Web-.

, . . Qt, .
Rectangle, Item. ,
(. 55.1).

VIII. Qt Quick

766

. 55.1.

55.1.

Item {
width: 360
height: 360
Rectangle {
color: "darkkhaki"
x: 100
y: 50
width: 170
height: 200
}
}

, 55.1 Item
, 360360 width
height. Rectangle
: 100 : 50 ( x y) 170200 ( width
height). color "darkkhaki".
, QML, .
border.color, radius smooth , . :
Rectangle {
...
border.color: "black"

55.

767

radius: 5
smooth: true
...
}


,
.
.
:
x, y, position ;
width, height ;
anchors (. 56);
id, parent .

55.1. . .
C++ , QML ,
, .
, .
id ,
. ,
id .

, id ,
, .

parent . (. 55.2)
parent id , parent, id .
55.2. parent id

Item {
width: 360
height: 360
Rectangle {
id: redrect;
color: "red"
x: 0
y: 0
width: parent.width / 2
height: parent.height / 2
}

VIII. Qt Quick

768
Rectangle {
color: "green";
x: redrect.width
y: redrect.height
width: redrect.width
height: redrect.height
}
}

. 55.2. id parent

55.2 . redrect ( id), ( color), 0, 0 ( x y). ( width height)


.
parent .
( color) x y
, ,
redrect.
( width height). , , ,
. ?
"" , ,
QML "", , , .
, , .
QML , ,
, onX
(onWidthChanged, onHeightChanged . .).
, , .

55.

769

55.3.

Item {
width: 200
height: 200
Rectangle {
width: parent.width
height: parent.height
onWidthChanged: {
console.log("width changed:" + width)
}
onHeightChanged: {
console.log("height changed:" + height)
}
}
}

55.3 onWidthChanged onHeightChanged . .


, JavaScript.


, ,
. property,
:
property <> <>[: <>]

,
. . . 55.1
.
55.1.

action

qaction

bool

, false true

color

date

YYYY-MM-DD

int

list

real

string

time

HH:MM:SS

url

, URL (Uniform Resource Locator, )

vercor3d

x-, y- z-

VIII. Qt Quick

770

. 55.3.

, Text, (. 55.3).
55.4.

Item {
width: 200
height: 200
Item {
id: myelement
property string name: "My Element"
property int ver: 1
property real pi: 3.14159
property bool condition: true
property url link: "http://www.bhv.com/"
}
Text {
x: 0
y: 0
text: myelement.name + "<br>"
+ myelement.ver + "<br>"
+ myelement.pi + "<br>"
+ myelement.condition + "<br>"
+ myelement.link
}
}

55.4 myelement Item


. Text
text.
onX,
. ,
myelement onConditionChanged, condition:
onConditionChanged: {
//do something
}

55.

771

onX- Qt Creator
.


.
. , . ,
, , .
, , components , :
import "../components"

components ,
:
import "http://www.maxschlee.com/qml/components"

, , Rectangle (. 55.4).
Qt Creator. TextField.qml,
, main.qml.

. 55.4.

55.5. . TextField.qml

import QtQuick 1.0


Rectangle {
property alias text: txt.text
property string name: "TextField"
width: txt.width
height: txt.height
Text {
id: txt
x: 0
y: 0
}
}

VIII. Qt Quick

772

55.5
Rectangle, Text.
. Text.
. ,
Rectangle.
(alias) . . - text Rectangle txt,
text, Text. , .
, width Rectangle .
, "" . , .
. ,
.
.
Rectangle Text. ( x y) ,
Rectangle.
55.6. . main.qml

import QtQuick 1.0


Item {
width: 150
height: 100
TextField {
x: 10
y: 20
color: "yellow"
text: "Text Text Text<br>Text Text Text"
border.width: 1
}
}

55.6 TextField. main.qml, .


x: 10 y: 20 ( x y).
( color). text, , , , . , , (
border.width).

55.

773

JavaScript QML
JavaScript .
? , - , QML JavaScript. , JavaScript
width:
Rectange {
width: parent.width / 5
}

JavaScript ,
.
,
width:
Rectangle {
width: {
var w = parent.width /5
consloe.debug("Current width:" + w)
return w
}
}

JavaScript . :
Rectangle {
function maximum(a, b)
{
return a > b ? a : b;
}
width: maximum(parent.width, 100)
}

JavaScript qml- .
myfunctions.js. qml-:
import "myfunctions.js" as MyScripts
Rectangle {
function maximum(a, b)
{
return a > b ? a : b;
}
width: MyScripts.maximum(parent.width, 100)
}

import as MyScripts , ,
. , , ,

774

VIII. Qt Quick

. , , qml- .
myfunctions.js, JavaScript-,
:
.pragma myfunctions

, QML.

QML.
, ,
.
, , ,
, .
.
, .
, JavaScript.

56

QML , , , Qt,
, . , , , ,
.
QML, , ,
.

(anchor) .
: .
.
,
. 56.1.
56.1.

Rectangle {
width: 360
height: 360
Text {
text: "Centered"
anchors.centerIn: parent
}
}

QML , . .
. ( 56.1) Text Rectangle,
Text Rectangle,

VIII. Qt Quick

776

. anchors.centerIn
Text parent. . 56.2
.

. 56.1.

. 56.2.

56.2.

Rectangle {
width: 360
height: 360
Text {
text: "Centered"
anchors.horizontalCenter: parent.horizontalCenter
anchors.verticalCenter: parent.verticalCenter
}
}

, . 56.2, ,
verticalCenter horizontalCenter (. 56.2). , . 56.1.

, , parent.horizontalCenter, parent.anchors.horizontalCenter.

, . , - , . , 56.3.
56.3.

Rectangle {
width: 360
height: 360

56.

777

Text {
text: "Text"
anchors.left: parent.left
anchors.right: parent.right
anchors.top: parent.top
anchors.bottom: parent.bottom
}
}

anchors fill,
.
. , 56.4
56.3.
. ,
, . , , ,
anchors.
C++. ,
. , . .
QML . .
56.3
anchors :
anchors {
left: parent.left
right: parent.right
anchors.top: parent.top
anchors.bottom: parent.bottom
}
56.4.

Rectangle {
width: 360
height: 360
Text {
text: "Text"
anchors.fill: parent
}
}

, , ( 56.5).
56.5.

Rectangle {
width: 360
height: 360

VIII. Qt Quick

778
Rectangle {
color: "lightgreen"
anchors.fill: text
}
Text {
id: text
text: "Text"
anchors.fill: parent
}
}

,
. fill,
, ,
, - .
, - (. 56.3).
, ,
- , , . .
, . 56.3
, .

. 56.3.

56.5

56.1

anchors.centerIn: parent. -

, - , (. 56.4).
, anchors
. (. 56.5).
56.6.

Item {
width: 360
height: 360

56.

779

Rectangle {
id: redrect
color: "red"
width: parent.width / 1.5
height: parent.height / 1.5
anchors.top: parent.top
anchors.left: parent.left
}
Rectangle {
opacity: 0.5
color: "green"
anchors.top: redrect.verticalCenter
anchors.bottom: parent.bottom
anchors.left: redrect.horizontalCenter
anchors.right: parent.right
}
}

. 56.4.

. 56.5.

56.6 redrect ,
. ( width height) ,
. , ( opacity) .
( top) ( verticalCenter)
. ( bottom) .
( left) (
horizontalCenter) , ( right) .
,
, .
. 56.6 . ,
.

VIII. Qt Quick

780

. 56.6.

56.7.

Item {
width: 360
height: 60
Rectangle {
id: redrect
color: "red"
anchors.left: parent.left
anchors.top: parent.top
anchors.bottom: parent.bottom
width: 60
}
Rectangle {
color: "yellow"
anchors.top: parent.top
anchors.bottom: parent.bottom
anchors.left: redrect.right
anchors.right: greenrect.left
}
Rectangle {
id: greenrect
color: "green"
anchors.right: parent.right
anchors.top: parent.top
anchors.bottom: parent.bottom
width: 100
}
}

56.7 ,
. 60 100.
( ) redrect greenrect,
. left right right
left . ,
.

56.

781

topMargin, bottomMargin,
leftMargin rightMargin, anchors,
. 56.7.

. 56.7.

. 56.8.

, , . 56.8.
56.8.

Item {
width: 360
height: 180
Rectangle {
color: "red"
anchors {
right: parent.horizontalCenter
left: parent.left
top: parent.top
bottom: parent.bottom
leftMargin: 5
topMargin: 5
rightMargin: 5
bottomMargin: 5
}
}
Rectangle {
color: "green"
anchors {
left: parent.horizontalCenter
right: parent.right
top: parent.top
bottom: parent.bottom
leftMargin: 20
topMargin: 20
rightMargin: 20

VIII. Qt Quick

782
bottomMargin: 20
}
}
}

56.8 : ,
( color).
( right), .
leftMargin, topMargin, rightMargin bottomMargin
5 . ,

20 . ,
,
.
, Offset; anchors 56.8,
:
verticalCenterOffset: 10
verticalCenter: parent.verticalCenter


,
Qt. . :
Row , Qt

QHBoxLayout;
Column , Qt

QVBoxLayout;
Grid , Qt
QGridLayout.


, . 56.9.

. 56.9.

56.

783

56.9.

Item {
width: 360
height: 160
Row {
anchors.centerIn: parent
spacing: 10
Rectangle {
width: 64; height: 64; color: "red"
}
Rectangle {
width: 64; height: 64; color: "blue"
}
Rectangle {
width: 64; height: 64; color: "green"
}
}
}

56.9 (
centerIn). , 10 . Row , 6464 .
, , 56.9 Row Column.
rows
column, . ,
. 56.10.

. 56.10.

56.10.

Item {
width: 200
height: 200
Grid {
rows: 2

VIII. Qt Quick

784
columns: 2
anchors.centerIn: parent
spacing: 10
Rectangle {
width: 64;
}
Rectangle {
width: 64;
}
Rectangle {
width: 64;
}
Rectangle {
width: 64;
}

height: 64; color: "red"

height: 64;color: "blue"

height: 64; color: "green"

height: 64; color: "black"

}
}

56.10 56.9 ,
rows columns ,
2, .

, Qt,
. QML , . .
, QML .

57

QML , . , , .

QML Qt. .
, SVG, ,
: "red", "green", "darkkhaki", "snow" . .
148 : www.neonway.com/colors.
#rrggbb, HTML:
"#FF0000", "#00FE00", "#0000AF" . . ,
, . Qt Creator
(. 57.1). ,
color,
Show Qt Quick Toolbar. ,
.
rgba() . :
Rectangle {
color: Qt.rgba(0.3, 0.45, 0.21)
opacity: 0.5
}

Qt Qt.red, , 17 (. . 17.1).
opacity.
. , . -

VIII. Qt Quick

786

0.5 .
17.

. 57.1. Qt Creator


QML : Image BorderImage.

QML, JPG, PNG SVG.

Image
Image , source. , ,
URL, .
Image (. 57.2) Qt Creator . , Image , Show Qt Quick Toolbar.
.

. 57.2. Image Qt Creator

57.

787

, / ( scale) ( rotation).
.
transformOrgin.
, :
Image {
...
transformOrigin: Item.Top
...
}

. 57.3 ,
Image .

. 57.3.

57.1.

Rectangle {
color: "aqua"
width: img.width
height: img.height
Image {
id: img
x: 0
y: 0

VIII. Qt Quick

788
smooth: true
source: "neonway.png"
scale: 0.65
rotation: 30.0
}
}

57.1 Rectangle, Image. "aqua" , ( width height),


img. Image. , 0, 0 ( x y). smooth true,
,
. source "neonway.png", . .
, . scale
. , .
. rotation
30 , . width height , . .
,
.
.
57.2 Image, , Image 57.1.
57.2.

Image {
id: img
x: 0
y: 0
smooth: true
source: "neonway.png"
transform: [
Scale {origin.x: width / 2
origin.y: height / 2
xScale: 0.65
yScale: 0.65
},
Rotation {origin.x: width / 2
origin.y: height / 2
angle: 30.0
}
]
}

transform. , . , -

57.

789

. QML ,
, . ,
: Scale Rotation. ( origin.x origin.y). Scale 0.65 : x y
( xScale yScale). Rotation angle
30 .

BorderImage
BorderImage . . .
,
. , , . 57.4. , left, right, top bottom.

. 57.4.

. 57.5.

,
.
. . 57.5 ,
.

790

VIII. Qt Quick

57.3.

BorderImage {
source: "button.png"
width: 100
height: 45
border {left: 30; top: 15; right: 30; bottom: 15}
}

57.3 source ,
. BorderImage
, ,
( width height). ,
left, top, right bottom.

QML .
gradient, Gradient.
( GradientStop).
, . . 0 ( ) 1 ( ),
.
. , . . 57.6 ,
.
57.4.

Rectangle {
width: 200
height: 200
gradient: Gradient {
GradientStop {position: 0.0; color: "blue"}
GradientStop {position: 0.7; color: "gold"}
GradientStop {position: 1.0; color: "silver"}
}
rotation: 30;
scale: 1.5
}

Rectangle ( 57.4) gradient Gradient,


GradientStop. 0,
0.7 1 ( position). ( color). ( rotation scale).
Qt Creator . gradient
Show Qt Quick Toolbar, , . 57.7.

57.

. 57.6.

791

. 57.7.
Qt Creator


.
,
. ,
, , , .
.
:
Rectangle {
width: 300
height: 300
Image {
x: 0;
y: 0
source: "../images/gradient.png"
}
}

font. Text Helvetica ( family), 24 (


pixelSize) ( bold):
Text {
...
font {
family: "Helvetica"
pixelSize: 24
bold: true
}
...
}

792

VIII. Qt Quick

Qt Creator.
font,
Show Qt Quick Toolbar. , . 57.8,
.

. 57.8. Qt Creator

, :
Image BorderImage, .
, ,
,
, .

58


..., .

QML .
.
.


QML ,
MouseArea " ". , , .
, , .
, ,
(. 58.1).

. 58.1.

58.1.

Rectangle {
width: 360
height: 200

VIII. Qt Quick

794

color: "lightgreen"
Text {
anchors.centerIn: parent
text: "<h1><center>Click Me!<br>
(use left & right buttons)</center></h1>"
}
MouseArea {
anchors.fill: parent
acceptedButtons: Qt.LeftButton | Qt.RightButton
onPressed: {
if (mouse.button == Qt.RightButton) {
parent.color = "red"
}
else {
parent.color = "blue"
}
}
onReleased: parent.color = "lightgreen"
}
}

58.1 - ( Text), . . ( MouseArea), Rectangle.


fill , ,
. , .
(onPressed onReleased), . , "on". Qt , ,
. .
,
, . onPressed mouse, , ,
.
,
. acceptedButtons

.
,


(. 58.2).

. 58.2.

58.

795

58.2. hover

Rectangle {
width: 200
height: 200
color: mousearea.containsMouse ? "red" : "lightgreen"
Text {
anchors.centerIn: parent
text: "<H1>Hover Me!</H1>"
}
MouseArea {
id: mousearea
anchors.fill: parent
hoverEnabled: true
}
}

58.2 , mousearea,
, ( Rectangle)
, .
.
hoverEnabled true. MouseArea .
onEntered
onExit. ,
, . . . 58.3.
58.3. hover,

Rectangle {
width: 200
height: 200
color: "lightgreen"
Text {
text: "<H1>Hover Me!</H1>"
anchors.centerIn: parent
}
MouseArea {
id: mousearea
anchors.fill: parent
hoverEnabled: true
onEntered: parent.color = "red"
onExited: parent.color = "lightgreen"
}
}

VIII. Qt Quick

796

58.3 , 58.2, hoverEnabled true .


onEntered MouseArea , onExited - .

Qt . , QML
. QML ,
. QML
. , ,
"on". , ,
, .
, , MouseArea onPressed, onReleased, onClicked . .
,
.
signal. :
signal <name>[(<type> <value>, ...)]

:
on<Name>: <expression>

.
. ,
. 58.3.

. 58.3.

58.4.

Rectangle {
width: 300
height: 150
signal mousePositionChanged(real x, real y)
onMousePositionChanged:
txt.text = "<h1>X:" + x + "; Y:" + y + "</h1>"

58.

797

Text {
id: txt
text: "<h1>Move the Mouse</h1>"
anchors.centerIn: parent
}
MouseArea {
anchors.fill: parent
hoverEnabled: true
onMousePositionChanged:
parent.mousePositionChanged(mouseX, mouseY)
}
}

58.4, signal, . : x y. , "on",


, Qt Creator -, onMousePositionChanged.
txt .
. , onMousePositionChanged
. , mouseX mouseY, . , , .
(. 58.4),
clicked. .

. 58.4.

58.5. . Button.qml

import QtQuick 1.0


BorderImage {
property alias text: txt.text
signal clicked;
source: "button.png"
width: txt.width + 15

VIII. Qt Quick

798
height: txt.height + 15
border {left: 15; top: 12; right: 15; bottom: 12}
Text {
id: txt
color: "white"
anchors.centerIn: parent
}
MouseArea {
anchors.fill: parent
onClicked: parent.clicked();
onPressed: parent.source = "buttonpressed.png"
onReleased: parent.source = "button.png"
}
}

.
. , 58.5,
Button.qml. BorderImage. Text, , , -. clicked,
,
onClicked . ,
BorderImage
15 . .
, onPressed onReleased.
58.6.

Item {
width: 150
height: 100
Button {
anchors.centerIn: parent
text: "Please, Click me!"
onClicked: {
text = "Clicked!"
}
}
}

, 58.6,
. text .
onClicked .
, . . -

58.

799

, . . . . : ,
, .
, ,
.
. , , ,
, !
,
clicked .
58.7. . Button.qml

import QtQuick 1.0


BorderImage {
property alias text: txt.text
property bool clicked;
source: "button.png"
width: txt.width + 15
height: txt.height + 15
border {left: 15; top: 12; right: 15; bottom: 12}
Text {
id: txt
color: "white"
anchors.centerIn: parent
}
MouseArea {
anchors.fill: parent
onPressed: {
parent.source = "buttonpressed.png"
parent.clicked = false
}
onReleased: {
parent.source = "button.png"
parent.clicked = true
}
}
}

58.7 58.5.
clicked . onPressed
onReleased.

800

VIII. Qt Quick

58.8.

Item {
width: 150
height: 100
Button {
anchors.centerIn: parent
text: "Please, Click me!"
onClickedChanged: {
text = "Clicked!"
}
}
}

, 58.6 58.8, , onClicked,


onClickedChanged, . . .


: TextInput
TextEdit. , . TextInput , TextEdit
, , Qt QLineEdit QTextEdit.
TextInput ,
. 58.5.

. 58.5.

58.9.

Rectangle {
width: 200
height: 100
TextInput {
anchors.centerIn: parent
color: "red"
text: "Text"
font.pixelSize: 32
focus: true
}
}

58.

801

58.9 . , , true ( focus).


. , TextInput ?
0, .
, width
.

. .
TextInput, .
, . , ,
focus. . 58.6
.
.

. 58.6.

58.10.

Item {
width: 200
height: 80
TextEdit {
anchors.left: parent.left
anchors.right: parent.horizontalCenter
anchors.top: parent.top
anchors.bottom: parent.bottom
text: "TextEdit1<br>TextEdit1<br>TextEdit1"
font.pixelSize: 20
color: focus ? "red" : "black"
focus: true
}
TextEdit {
anchors.left: parent.horizontalCenter
anchors.right: parent.right
anchors.top: parent.top
anchors.bottom: parent.bottom
text: "TextEdit2<br>TextEdit2<br>TextEdit2"

VIII. Qt Quick

802
font.pixelSize: 20
color: focus ? "red" : "black"
}
}

( 58.10). , focus, . , , , ,

, .
, , . . . , . 58.7,
: , . - . .

. 58.7.

58.11.

Rectangle {
width: 300
height: 300
color: focus ? "red" : "lightgreen"
KeyNavigation.tab: childrect
Rectangle {
id: childrect
width: 150
height: 150
anchors.centerIn: parent
color: focus ? "red" : "lightgreen"

58.

803

KeyNavigation.tab: parent
focus: true
Text {
anchors.centerIn: parent
text: "Press TAB"
}
}
}

58.11
KeyNavigation.tab. Rectangle.
,
focus color . ( focus).
KeyNavigation.tab, ,
, , .
, , , KeyNavigation.right,
KeyNavigation.left, KeyNavigation.up KeyNavigation.down.

""
. , Keys. , (. 58.8).

. 58.8.

58.12.

Rectangle {
width: 200
height: 100
Text {
x: 20;
y: 20;
text: "Move this text<br>(use the cursor-keys)"
horizontalAlignment: Text.AlignHCenter
Keys.onLeftPressed: x -= 3

VIII. Qt Quick

804
Keys.onRightPressed: x += 3
Keys.onDownPressed: y += 3
Keys.onUpPressed: y -= 3
focus: true
}
}

58.12 :
< > (Keys.onLeftPressed), < >
(Keys.onRightPressed), < > (Keys.onDownPressed) < >
(Keys.onUpPressed).
3 . . 58.13
,
onPressed, , :
58.13.

Keys.onPressed: {
if (event.key == Qt.Key_Left) {
x -= 3;
}
else if (event.key == Qt.Key_Right) {
x += 3;
}
else if (event.key == Qt.Key_Down) {
y += 3;
}
else if (event.key == Qt.Key_Up) {
y -= 3;
}
}

58.13 ( event.key) Qt (. . 14.2).


Keys.forwardTo
, .

MouseArea.
,
.
" on". Qt Creator,
.
TextInput TextEdit,
.
KeyNavigation Keys.

59

, ,
, .
.

22. ,
? , ,
, Qt, QML , . . .
.
,
,
. ,
, .
, , . , , . , -, , . . , .
, , , .
.
, QML , ,
. ,
. , "" QML. QML: real, int, color, rect, point, size vector3d.


PropertyAnimation. ,
. , . 59.1,
: x y,
.

806

VIII. Qt Quick

. 59.1.
x y

59.1. x y

Rectangle {
color: "lightgreen"
width: 300
height: 300
Image {
id: img
x: 0
y: 0
source: "happyos.png"
}
PropertyAnimation {
target: img
properties: "x,y"
from: 0
to: 300 img.height
duration: 1500
running: true
loops: Animation.Infinite
easing.type: Easing.OutExpo
}
}

59.1 Image
ProperyAnimation Rectangle. target , .
propeties , . from , to
. ,
0 ,
. , -

59.

807

, duration,
1,5 . , ,
, running
true. loop ,
Animaion.Infinite, .
. , , .
easing.type. Qt , QML-,
. 22.1 . , Qt Creator,
easing.type, Show Qt
Quick Toolbar, , . 59.2.

. 59.2.

,
. .
. , , , .
, PropertyAnimation. :
NumberAnimation ;
ColorAnimation ;
RotationAnimation .


NumberAnimation , PropertyAnimation,
real int. (. 59.3).

VIII. Qt Quick

808

. 59.3. NumberAnimation

59.2. NumberAnimation

Rectangle {
width: 300
height: 100
color: "lightgreen"
Rectangle {
x: 0
y: 0
height: 100
color: "red"
NumberAnimation on width {
from: 300
to: 0
duration: 2000
easing.type: Easing.InOutCubic
}
}
}

59.2 ,
-, ( color).
100 ( height). NumberAnimation
" on",
width. (from, to, duration, easing.type) ,
PropertyAnimation (. 59.1).


ColorAnimation
from to. , . 59.4, .
59.3. ColorAnimation

Rectangle {
width: 200
height: 200

59.

809

ColorAnimation on color {
from: Qt.rgba(1, 0.5, 0, 1)
to: Qt.rgba(0.5, 0, 1, 1)
duration: 1500
running: true
loops: Animation.Infinite
}
}

59.3 from to,


. . ,
, 1,5 (
duration). true running .

. 59.4.
ColorAnimation

. 59.5.
RotationAnimation


RotationAnimation .
direction, .
:
RotationAnimation.Clockwise ;
RotationAnimation.Counterclockwise ;
RotationAnimation.Shortest -

, from, to.
.
RotationAnimation (. 59.5).
59.4. RotationAnimation

Rectangle {
width: 150
height: 150

VIII. Qt Quick

810
Image {
source: "happyos.png"
anchors.centerIn: parent
smooth: true
RotationAnimation on rotation {
from: 0
to: 360
duration: 2000
loops: Animation.Infinite
easing.type: Easing.InOutBack
}
}
}

59.4 RotationAnimation
Image. 2 ( ) 0 360.


, ,
- . , , , "" , . ,
, , .
Behavior.
, . 59.6,
.

. 59.6.

59.

811

59.5.

Rectangle {
id: rect
width: 360
height: 360
Image {
id: img
source: "happyos.png"
x: 10
y: 10
smooth: true
Text {
anchors.verticalCenter: img.verticalCenter
anchors.top: img.bottom
text: "Move the mouse!"
}
Behavior on x {
NumberAnimation {
duration: 1000
easing.type: Easing.OutBounce
}
}
Behavior on y {
NumberAnimation {
duration: 1000
easing.type: Easing.OutBounce
}
}
}
MouseArea {
anchors.fill: rect
hoverEnabled: true
onMousePositionChanged: {
img.x = mouseX
img.y = mouseY
}
}
}

59.5 Behavior, x y Image.


NumberAnimation
1 . , .
Image
MouseArea onMousePositionChanged.

VIII. Qt Quick

812

, .
, ?
. .
.
SequentialAnimation.
. ,
.
ParallelAnimation , . , .
.
, , :
Rectangle {
....
PropertyAnimation on x {to: 50; duration: 1000}
PropertyAnimation on y {to: 50; duration: 1000}
....
}

, (. 59.7).

.

. 59.7.

59.

813

59.6.

Rectangle {
width: 400
height: 400
Image {
id: img
source: "happyos.png"
smooth: true
anchors.centerIn: parent
}
ParallelAnimation {
NumberAnimation {
target: img
properties: "scale"
from: 0.1;
to: 3.0;
duration: 2000
easing.type: Easing.InOutCubic
}
NumberAnimation {
target: img
properties: "opacity"
from: 1.0
to: 0;
duration: 2000
}
running: true
loops: Animation.Infinite
}

. 59.8.

59.6 : ( scale) 1 3 ( opacity)


( 1 0). ,
, Image, target img. 2 (
duration). ,
, running true, , loop Animation.Infinite.
, , ,
. , . , , , , , , .
, , .
. 59.8 , , . . .

814

VIII. Qt Quick

59.6.

Rectangle {
width: 130
height: 450
Image {
id: img
source: "happyos.png"
smooth: true
Text {
anchors.horizontalCenter: img.horizontalCenter
anchors.top: img.bottom
text: "Click me!"
}
MouseArea {
anchors.fill: img
onClicked: anim.running = true
}
SequentialAnimation {
id: anim
NumberAnimation {
target: img
from: 20
to: 300
properties: "y"
easing.type: Easing.OutBounce
duration: 1000
}
RotationAnimation {
target: img
from: 0
to: 360
properties: "rotation"
direction: RotationAnimaion.Clockwise
duration: 1000
}
PauseAnimation {
duration: 500
}
NumberAnimation {
target: img
from: 300
to: 20
properties: "y"
easing.type: Easing.OutBack
duration: 1000
}
}
}
}

59.

815

59.6 , .
onClicked MouseArea. ( running), anim.
( SequentialAnimation).
NumberAnimation
20 ( from) 300 ( to) ( y). 1 ( duration).
, RotationAnimation,
from to 0 360 .
direction, , . .
( RotationAnimation.Clockwise)
. 1 .
, . .
" ".
duration ,
500, . . 0,5 .
.
NumberAnimation, y
300 20 ( from to).
0,5 ( duration).


, . , , ,
"A", "B".
, . ,
, 2530 ,
. :
"A" "B"? , , - .
, - .

QML State. , . . . ,
.
JavaScript,
.
, , .

VIII. Qt Quick

816

. 59.9. ()

. 59.10. ()

. . 59.9 ,
. 59.10 , .
59.7.

Rectangle {
id: rect
width: 360
height: 360
state: "State2"
Text {
id: txt
anchors.centerIn: parent
}
states: [
State {
name: "State1"
PropertyChanges {
target: rect
color: "lightgreen"
width: 150
height: 60
}
PropertyChanges {
target: txt
text: "State2: Click Me!"
}
},
State {
name: "State2"

59.

817

PropertyChanges {
target: rect
color: "yellow"
width: 200
height: 120
}
PropertyChanges {
target: txt
text: "State1: Click Me!"
}
}
]
MouseArea {
anchors.fill: parent
onClicked:
parent.state = (parent.state == "State1") ? "State2" : "State1"
}
}

Qt Creator main.qml ( 59.7) ( Rectangle), ( Text). id . ,


:
rect, txt.
.
, QML.
states. . , ,
state. ,
State2. , ,
.

, ,
"".
state , ,
"State1".

. ,
. PropertyChanges. ,
, target. ,
. ,
.
color, width height Rectangle, Text text.
, .

VIII. Qt Quick

818

Rectangle. onClicked
, . state "State1", "State2", .
, 59.7 . , . . .

, UML (Unified Modeling Language, ), Rational Rose.
.

,
.
, , . . , .
, ,
, . , QML " ,
, ". , . , , , , . . .
.
. , ,
. 59.11 59.12, .

. 59.11. State1

. 59.12. State2

59.
59.8.

Item {
width: 300
height: 300
Rectangle {
id: rect
width: 100
height: 100
color: "magenta"
state: "State1"
Text {
anchors.centerIn: parent
text: "Click me!"
}
MouseArea {
anchors.fill: rect
onClicked:
rect.state = (rect.state == "State1") ? "State2" : "State1"
}
states: [
State {
name: "State1"
PropertyChanges {target: rect; x: 0; y: 0}
},
State {
name: "State2"
PropertyChanges {target: rect; x: 200; y: 200}
}
]
transitions: [
Transition {
from: "State1"; to: "State2"
PropertyAnimation {
target: rect;
properties: "x,y";
easing.type: Easing.InCirc
duration: 1000
}
},
Transition {
from: "State2"; to: "State1"
PropertyAnimation {
target: rect
properties: "x,y";
easing.type: Easing.InBounce
duration: 1000
}
}
]
}
}

819

820

VIII. Qt Quick

59.7, 59.8
.
transitions . Transition .
.
from to, . .
State1 State2,
, . . State2 State1.
PropertyAnimation. ""
.
,
duration. 1 . easing.type .
( Easing.InCirc Easing.InBounce).
,
PropertyAnimation ,
. transitions 58.8 , 58.9, .
59.9.

transitions:
Transition {
from: "*"; to: "*"
PropertyAnimation {
target: rect;
properties: "x,y";
easing.type: Easing.InCirc
duration: 1000
}
}

"*" (. . 59.9).
, . ,
, 59.8.
Easing.InCirc.

. , QML, , , . , ,
, C++.

59.

821

QML .
PropertyAnimation.
. .
Qt Creator
.
-. .
.
.
.
.
.
.

60

/
, .

QML, Interview, Qt,


. , ,
.

, , , .
, . , QML, ListModel
XmlListModel. , C++
(. 61), , , QML.
QML.


ListModel :
ListModel {
ListElement{...}
ListElement{...}
...
}

ListElement .
ListElement . -
artist (), album (), year () cover ().

60. /

823

60.1. . CDs.qml

ListModel {
ListElement {
artist: "Amaranthe"
album: "Amaranthe"
year: 2011
cover: "covers/Amaranthe.png"
}
ListElement {
artist: "Dark Princess"
album: "Without You"
year: 2005
cover: "covers/WithoutYou.png"
}
ListElement {
artist: "Within Temptation"
album: "The Unforgiving"
year: 2011
cover: "covers/TheUnforgiving.png"
}
...
}

60.1 . , -
(CD), cover CD.
,
ListModel . ,
, append(),
insert(), remove() move().
CDs.qml,
, ,
, id . .

XML-
, XML-. Web-.
. XmlListModel
XML-.
XPath (. 41) .
,
, XML-.
.

824

VIII. Qt Quick

60.2. XML-. CDs.xml

<?xml version = "1.0"?>


<CDs>
<CD>
<artist>Amaranthe</artist>
<album>Amaranthe</album>
<year>2011</year>
<cover>covers/Amaranthe.png</cover>
</CD>
<CD>
<artist>Dark Princess</artist>
<album>Without You</album>
<year>2005</year>
<cover>covers/WithoutYou.png</cover>
</CD>
<CD>
<artist>Within Temptation</artist>
<album>The Unforgiving</album>
<year>2011</year>
<cover>covers/TheUnforgiving.png</cover>
</CD>
...
</CDs>

, 60.2 XML-. . 60.1.


CDs.xml .
, . XmlListModel.
60.3. XML-. CDs.qml

XmlListModel {
source: "CDs.xml"
query: "/CDs/CD"
XmlRole {name: "artist"; query: "artist/string()"}
XmlRole {name: "album"; query: "album/string()"}
XmlRole {name: "year"; query: "year/string()"}
XmlRole {name: "cover"; query: "cover/string()"}
}

60.3 . XmlListModel source, , XML- , . .


XML- ,
60.2.
, XPath.
. , -

60. /

825

, XML-. , , , XmlRole. . name , , query .


query .
. &q