1、QT GUI 编程,QT编程基础,I、QT介绍,Qt 是一个跨平台应用程序和 UI 开发框架只需一次性开发应用程序,无须重新编写源代码,便可跨不同桌面和嵌入式操作系统部署这些应用程序 Qt完全的面向对象、易于扩展,并允许组件编程,I、QT介绍,QT类库 模块化 Qt C+ 类库提供一套丰富的应用程序生成块 (block),包含了生成高级跨平台应用程序所需的全部功能。,I、QT介绍,QT官方网站 http:/ 相关学习资源 http:/ http:/www.qtcn.org http:/,I、QT介绍,Qt 开发环境搭建 下载Qt SDK http:/,I、QT介绍,选择相应版本的Qt SDK下
2、载安装,I、QT介绍,环境变量设置 添加路径,一、Hello,World,QT GUI工程创建 QT工程目录结构 Hello World程序分析,例程 t1,一、Hello,World,头文件 对于每个Qt类,都有一个与该类同名的头文件,这个头文件中包括了该类的定义 #include :“QtGui”头文件中包含了GUI程序设计中常用的类的头文件main( int argc, char *argv ) 程序入口 使用Qt编程时,main()仅用于在进入Qt library前的一些初始化工作 argc:命令行参数个数 argv:命令行参数序列,一、Hello,World,QApplication
3、类 用于管理整个GUI应用程序所用到的资源(resources)、控制流(control flow)和主要设置(main settings) contains the main event loop 每个GUI程序仅有一个QApplication对象 (无论该程序有多少个窗体) qApp宏 指向QApplication对象的全局指针 #define qApp QCoreApplication:instance() 常用属性和函数 int QApplication:exec() 进入主事件循环(event loop),直到程序退出。 程序正常退出时返回 0 QString QCoreApplic
4、ation:applicationDirPath () QString QCoreApplication:applicationFilePath () 返回程序路径,二、 Calling it Quits,更改按钮字体 加入点击按钮退出程序功能,例程 t2,二、 Calling it Quits,int main( int argc, char *argv ) quit.setFont( QFont( “Times“, 18, QFont:Bold ) );QObject:connect( ,二、 Calling it Quits,窗口部件的字体属性: font : QFont 成员访问函数:
5、 const QFont & font ( ) const void setFont ( const QFont & ) QFont类 QFont用于指定显示文本时的字体 常用函数 QFont:QFont (const QString & family, int pointSize = -1,int weight = -1, bool italic = false ) family:字体类型,如“Times”、“Arial”等如果字体类型无效时,将使用最接近的字体代替 pointSize:字号,值0时使用系统定义的默认值 weight:字体粗细。 0 99可以使用预定义值 italic:是否使
6、用斜体,二、 Calling it Quits,QFont类 常用函数 QFont:QFont (const QString & family, int pointSize = -1,int weight = -1, bool italic = false )void QFont:setFamily ( const QString & family ) void QFont:setPointSizeF ( qreal pointSize ) void QFont:setWeight ( int weight ) void QFont:setItalic ( bool enable ),QFon
7、t serifFont(“Times“, 10, QFont:Bold); QFont sansFont(“Helvetica Cronyx“, 12);,QFont serifFont();serifFont.setFamily(“Times“);serifFont.setPointSizeF(10);serifFont.setWeight(QFont:Bold);serifFont.setItalic(false);,二、 Calling it Quits,信号-槽(Signals & Slots),quit:QPushButton,click() signal,a:QApplicatio
8、n,quit() slot,QObject:connect( ,二、 Calling it Quits,信号和槽是用于对象间通信的一种机制,它可以让编程人员把那些互不了解的对象绑定在一起 信号和槽机制是Qt主要特色之一 信号和槽机制取代传统的CallBacks技术,Signals and slots are used for communication between objects. The signals and slots mechanism is a central feature of Qt and probably the part that differs most from t
9、he features provided by other frameworks.,A callback is a pointer to a function.If you want a processing function to notify you about some event, you pass a pointer to another function (the callback) to the processing function.,Fundamental flaws: (1) not type-safe. (2) the callback is strongly coupl
10、ed to the processing function (the processing function must know which callback to call.),二、 Calling it Quits,Qt类中预定义了大部分常用的信号与槽,同时用户可以自定义信号与槽 信号的声明发出信号,class 类名 : public QObject 或 其派生类 Q_OBJECTsignals :信号名(信号参数列表);;,含有信号与槽的类必须继承自QObject类或其派生类 类定义开始处需要有Q_OBJECT宏 在signals部分声明信号 信号的声明与函数声明相同,但是没有函数定义,
11、emit 信号名(信号参数表);,二、 Calling it Quits,槽的声明与定义,class 类名 : public QObject 或 其派生类 Q_OBJECT访问权限 slots :槽函数名(参数列表);;,含有信号与槽的类必须继承自QObject类或其派生类 类定义开始处需要有Q_OBJECT宏 在slots部分声明槽 访问权限 public private protected 槽与普通C+函数几乎完全一样,唯一不同的是它可以和信号连接,返回类型 类名:槽函数头 槽函数定义 ,二、 Calling it Quits,信号与槽的连接sender:指向发出信号的对象的指针 rece
12、iver:指向结束信号的对象的指针一个信号可以连接多个槽,发射信号时会以不确定的顺序自动调用这些槽 多个信号可以连接同一个槽 一个信号可以与另外一个信号连接 连接可以被移除: QObject:disconnect (.) 连接在一起的信号和槽的参数必须具有相同的顺序和类型信号与槽机制是通过Qt的元对象系统(meta-object system)的实现的,QObject:connect( sender, SINGAL( 信号名(参数类型表) ),receiver, SLOT( 槽名(槽参数类型表) ) );,二、 Calling it Quits,信号-槽 例程,/ counter.h #inc
13、lude class Counter : public QObject Q_OBJECT public: Counter() m_value = 0; int value() const return m_value; public slots: void setValue(int value); signals: void valueChanged(int newValue); private: int m_value; ; / counter.cpp #include “counter.h“ void Counter:setValue(int value) if (value != m_v
14、alue) m_value = value; emit valueChanged(value); / main.cpp #include “counter.h“main() Counter a, b;QObject:connect(/ a.value()=12/ b.value()=48 ,QTEXP3_1,二、 Calling it Quits,信号和槽的扩展阅读,三、 Layout & Parent-Child Widgets,设定窗口部件的位置,例程 t3_1 t3_2 t3_3,三、 Layout & Parent-Child Widgets,直接定位窗口部件的位置(设置 窗口部件的g
15、eometry 属性),geometry : QRectThis property holds the geometry of the widget relative to its parent.,const QRect & geometry () constvoid setGeometry( int x, int y, int w, int h )void setGeometry( const QRect & ),三、 Layout & Parent-Child Widgets,QWidget的坐标,三、 Layout & Parent-Child Widgets,扩展阅读,三、 Layou
16、t & Parent-Child Widgets,使用 Layout Class 布局,Qt includes a set of layout management classes that are used to describe how widgets are laid out in an applications user interface. These layouts automatically position and resize widgets.,class QLayout : public QObject, public QLayoutItem ,三、 Layout & Pa
17、rent-Child Widgets,三、 Layout & Parent-Child Widgets,A QHBoxLayout lays out widgets in a horizontal row, from left to rightA QVBoxLayout lays out widgets in a vertical column, from top to bottom.,三、 Layout & Parent-Child Widgets,A QGridLayout lays out widgets in a two-dimensional grid. A QFormLayout
18、lays out widgets in a 2-column descriptive label- field style.,三、 Layout & Parent-Child Widgets,All QWidget subclasses can use layouts to manage their children.,QWidget:setLayout(QLayout * layout) Sets the layout manager for this widget to layout., QVBoxLayout *layout = new QVBoxLayout;layout-addWid
19、get(formWidget);,三、 Layout & Parent-Child Widgets,HBox 、VBox,QVBoxLayout:QVBoxLayout () / QHBoxLayout:QHBoxLayout () Constructs a new vertical/horizontal box. You must add it to another layout or widget.QVBoxLayout:QVBoxLayout ( QWidget * parent ) QHBoxLayout:QHBoxLayout ( QWidget * parent ) Constru
20、cts a new top-level vertical/ horizontal box with parent parent.,void QLayout:addWidget ( QWidget * w ) Adds widget w to this layout in a manner specific to the layout.,void QBoxLayout:addLayout ( QLayout * layout ) Adds layout to the end of the box, with serial stretch factor stretch.,例程 t3_2,三、 La
21、yout & Parent-Child Widgets,void QBoxLayout:addStretch ( int stretch = 0 ) Adds a stretchable with zero minimum size and stretch factorspace to the box layout.,三、 Layout & Parent-Child Widgets,void QBoxLayout:addSpacing ( int size ) Adds a non-stretchable space with size size to the box layout. QBox
22、Layout provides default margin and spacing. This function adds additional space.,三、 Layout & Parent-Child Widgets,QGridLayout,he QGridLayout class lays out widgets in a grid. Normally, each managed widget or layout is put into a cell of its own using addWidget() or addLayout(). It is also possible f
23、or a widget to occupy multiple cells using the row and column spanning overloads of addWidget() or addLayout.,QGridLayout:QGridLayout ( QWidget * parent ) Constructs a new QGridLayout with parent widget parent. The layout has one row and one column initially, and will expand when new items are inser
24、ted. QGridLayout:QGridLayout () Constructs a new grid layout. You must insert this grid into another layout or widget.,三、 Layout & Parent-Child Widgets,void QGridLayout:addWidget ( QWidget * widget, int row, int column, Qt:Alignment alignment = 0 ) Adds the given widget to the cell grid at row, colu
25、mn. The top-left position is (0, 0) by default. The alignment is specified by alignment. The default alignment is 0, which means that the widget fills the entire cell.,void QGridLayout:addWidget ( QWidget * widget, int fromRow, int fromColumn, int rowSpan, int columnSpan,Qt:Alignment alignment = 0 )
26、 This is an overloaded function. This version adds the given widget to the cell grid, spanning multiple rows/columns.,三、 Layout & Parent-Child Widgets,void QGridLayout:addLayout ( QLayout * layout, int row, int column, Qt:Alignment alignment = 0 ) Places the layout at position (row, column) in the g
27、rid.,void QGridLayout:addLayout ( QLayout * layout, int row, int column, int rowSpan, int columnSpan, Qt:Alignmentalignment = 0 ) This is an overloaded function. This version adds the layout layout to the cell grid, spanning multiple rows/columns.,例程 t3_3,三、 Layout & Parent-Child Widgets,Alignment,三
28、、 Layout & Parent-Child Widgets,alignment = Qt:AlignHCenter,alignment = 0,alignment = Qt:AlignRight,三、 Layout & Parent-Child Widgets,void QGridLayout:setColumnMinimumWidth ( int column, int minSize ) Sets the minimum width of column column to minSize pixels.void QGridLayout:setRowMinimumHeight ( int
29、 row, int minSize ) Sets the minimum height of row row to minSize pixels.,三、 Layout & Parent-Child Widgets,QWidget:minimumSize : QSize QWidget:maximumSize : QSize,This property holds the widgets minimum/maximum size. The widget cannot be resized to a smaller size than the minimum widget size. The wi
30、dget cannot be resized to a larger size than the maximum widget size.,void setMaximumSize ( const QSize ,三、 Layout & Parent-Child Widgets,pBtnThree-setMaximumSize( 100,50 );,pBtnThree-setMinimumSize( 200,50 );,三、 Layout & Parent-Child Widgets,扩展阅读,四、Create Your Own Widget,四、Create Your Own Widget,Ho
31、w to create your own widget How to control the minimum and maximum sizes of a widget,例程 t4,四、Create Your Own Widget,class MyWidget : public QWidget ,Here we create a new class. Because this class inherits from QWidget, the new class is a widget and may be a top level window or a child widget.,MyWidg
32、et:MyWidget(QWidget *parent): QWidget(parent) QPushButton *quit = new QPushButton( “Quit“, this ); MyWidget:MyWidget() / delte quit; ? ,Note that quit is a local variable in the constructor. MyWidget does not keep track of it, but Qt does, and will by default delete it when MyWidget is deleted.,四、Cr
33、eate Your Own Widget,QWidget,The QWidget class is the base class of all user interface objects. The widget is the atom of the user interface It receives mouse, keyboard and other events from the window system Paints a representation of itself on the screen. Every widget is rectangular They are sorte
34、d in a Z-order. A widget is clipped by its parent and by the widgets in front of it.,四、Create Your Own Widget,Top-Level and Child Widgets,Top-Level Widgets A widget without a parent widget is called a window (top-level widget). Usually, windows have a frame and a title bar(although it is also possib
35、le to create windows without such decoration using suitable window flags). For these widgets, setWindowTitle() and setWindowIcon() set the title bar and icon respectively.,Child Widgets Non-window widgets are child widgets, displayed within their parent widgets. Most widgets in Qt are mainly useful
36、as child widgets.,四、Create Your Own Widget,QWidget 常用属性和函数 构造函数,QWidget:QWidget ( QWidget * parent = 0, Qt:WindowFlags f = 0 ) Constructs a widget which is a child of parent, with widget flags set to f.QWidget * parent : The parent of the new widget. If it is 0 (the default), the new widget will be
37、a window. If not, it will be a child of parent, and be constrained by parents geometry (unless you specify Qt:Window as window flag). Qt:WindowFlags f : Sets the window flags The default is suitable for almost all widgets You can use special flags.,四、Create Your Own Widget,Qt:WindowFlags,Qt:WindowFl
38、ags windowFlags () constvoid setWindowFlags ( Qt:WindowFlags type ),四、Create Your Own Widget,f=0,Qt:Dialog,Qt:ToolTip,Qt:SubWindow,Qt:CustomizeWindowHint|Qt:WindowTitleHint|Qt:WindowCloseButtonHint,Qt:WindowStaysOnTopHint,四、Create Your Own Widget,扩展阅读,五、Create Composite Widget,Composite Widgets,When
39、 a widget is used as a container to group a number of child widgets, it is known as a composite widget. Composite widgets can be created by subclassing a standard widget, such as QWidget or QFrame, and adding the necessary layout and child widgets in the constructor of the subclass.,五、Create Composi
40、te Widget,How to create composite widget How to create and connect together several widgets by using signals and slots How to use QLCDNumber How to use QSlider,例程 t5,五、Create Composite Widget,QLCDNumberQLCDNumber常用属性和函数 构造函数,The QLCDNumber widget displays a number with LCD-like digits. It can displa
41、y decimal, hexadecimal, octal or binary numbers. QLCDNumber emits the overflow() signal when it is asked to display something beyond its range.,QLCDNumber:QLCDNumber ( QWidget * parent = 0 ) Constructs an LCD number, sets the base to decimal, the decimal point mode to small and the frame style to a
42、raised box.,五、Create Composite Widget,QLCDNumber常用属性和函数 digitCount : int,Access functions int digitCount()const void setDigitCount( int numDigits ),This property holds the current number of digits displayed. By default, this property contains a value of 5.,五、Create Composite Widget,QLCDNumber常用属性和函数
43、 value : double,Access functions double value () const void display ( const QString & s ) slot void display ( int num ) slot void display ( double num ) slot,This property holds the displayed value. By default, this property contains a value of 0.,五、Create Composite Widget,QLCDNumber常用属性和函数 mode : M
44、ode,Access functions Mode mode () const void setMode ( Mode ),This property holds the current display mode (number base). mode is one of Bin, Oct, Dec (the default) and Hex. Dec mode can display floating point values, the other modes display the integer equivalent.,See also void setHexMode() slot vo
45、id setDecMode() slot void setOctMode() slot void setBinMode() slot,五、Create Composite Widget,QLCDNumber常用属性和函数 segmentStyle : SegmentStyle,Access functions SegmentStyle segmentStyle () const void setSegmentStyle ( SegmentStyle ),This property holds the style of the LCDNumber.,五、Create Composite Widg
46、et,QLCDNumber常用属性和函数 overflow () signal,This signal is emitted whenever the QLCDNumber is asked to display a too-large number or a too-long string.,五、Create Composite Widget,扩展阅读,五、Create Composite Widget,QSliderQSlider常用属性和函数 构造函数,The QSlider widget provides a vertical or horizontal slider.,QSlider
47、:QSlider ( Qt:Orientation orientation, QWidget * parent = 0 ) Constructs a slider with the given parent.orientation: determines whether the slider is horizontal(Qt:Horizontal) or vertical(Qt:Verticaland),五、Create Composite Widget,QSlider常用属性和函数 maximum : int / minimum : int,Access functions int maxi
48、mum () const int minimum () const void setMaximum ( int ) void setMinimum ( int ),This property holds the sliders maximum/minimum value.,See also void setRange ( int min, int max ),五、Create Composite Widget,QSlider常用属性和函数 singleStep : int / pageStep : int,Access functions int pageStep () const int s
49、ingleStep () const void setPageStep ( int ) void setSingStep ( int ),This property holds the single/page step. signalStep corresponds to the user pressing an arrow key pageStep corresponds to the user pressing PageUp or PageDown,五、Create Composite Widget,QSlider常用属性和函数 value : int,Access functions int value () const void setValue ( int ) slot,