关闭

关闭

关闭

封号提示

内容

首页 QT总结资料.doc

QT总结资料.doc

QT总结资料.doc

上传者: asdsa 2010-12-18 评分 0 0 0 0 0 0 暂无简介 简介 举报

简介:本文档为《QT总结资料doc》,可适用于IT/计算机领域,主题内容包含QT总结资料QT总结资料QT中取消最大化最小化关闭按钮的代码。首先在主函数main中,比如窗口是mainwindowIntmain(intargcc符等。

QT总结资料QT总结资料QT中取消最大化最小化关闭按钮的代码。首先在主函数main中,比如窗口是mainwindowIntmain(intargccharargv){QApplicationa(argc,argv)MainWindowwwsetWindowFlags(wsetWindowflags()~Qt::WindowMaximizeButtonHint~Qt::WindowMinimizeHint)wshowMinimized()取消最大化最小化按钮只是显示关闭按钮显示。wshowMaximized()取消最大化最小化按钮只是显示关闭按钮但是整个屏幕显示。wshowFullScreen()全屏显示取消窗口菜单栏显示窗体。returnaexec()}键盘快捷事件的代码编写。QT中做一个当前时钟。#include<QtCore>#include<QtGui>classDigits:publicQWidget{QOBJECTpublic:*Definethreetransitionmodesofthedigitalclock*enum{Slide,Flip,Rotate}Digits(QWidget*parent):QWidget(parent),mnumber(),mtransition(Slide){setAttribute(Qt::WAOpaquePaintEvent,true)WidgetpaintsallitspixelswhenitreceivesapainteventsetAttribute(Qt::WANoSystemBackground,true)Indicatesthatthewidgethasnobackground,iewhenthewidgetreceivespaintevents,thebackgroundisnotautomaticallyrepaintedconnect(manimator,SIGNAL(frameChanged(int)),SLOT(update()))startanimationmanimatorsetFrameRange(,)manimatorsetDuration()ConstructasecondtimelinewithaframerangeofmanimatorsetCurveShape(QTimeLine::EaseInOutCurve)startsgrowingslowly,thenrunssteadily,thengrowsslowlyagain}*Settransitionwhentimechanged*voidsetTransition(inttr){mtransition=tr}*Gettransitionmode*inttransition()const{returnmtransition}*Sethoursandminutes*voidsetNumber(intn){if(mnumber!=n){mnumber=qBound(,n,)preparePixmap()update()}}*Fliptonextstate*voidflipTo(intn){if(mnumber!=n){mnumber=qBound(,n,)mlastPixmap=mpixmappreparePixmap()manimatorstop()manimatorstart()}}protected:*Drawthemainframeofthedigitsarea*voiddrawFrame(QPainter*p,constQRectrect){p>setPen(Qt::NoPen)QLinearGradientgradient(recttopLeft(),rectbottomLeft())SetlineargradientareagradientsetColorAt(,QColor(,,))gradientsetColorAt(,QColor(,,))gradientsetColorAt(,QColor(,,))gradientsetColorAt(,QColor(,,))Createsstoppointsatthegivenpositionwiththegivencolorp>setBrush(gradient)QRectr=rectp>drawRoundedRect(r,,,Qt::RelativeSize)*DrawsouterrectanglerectwithroundedcornersQt::RelativeSizespecifiesthesizerelativetotheboundingrectangle,typicallyusingpercentagemeasurements*radjust(,,,)Adds,,andrespectivelytotheexistingcoordinatesoftherectanglep>setPen(QColor(,,))p>setBrush(Qt::NoBrush)p>drawRoundedRect(r,,,Qt::RelativeSize)Drawsinnerrectanglerectwithroundedcornersp>setPen(QColor(,,))inty=recttop()rectheight()p>drawLine(rectleft(),y,rectright(),y)Drawsthemidlinefrom(rectleft(),y)to(rectright(),y)andsetsthecurrentpenpositionto(rectright(),y)}*Drawthedigits*QPixmapdrawDigits(intn,constQRectrect){intscaleFactor=#ifdefined(QOSSYMBIAN)||defined(QOSWINCEWM)if(rectheight()>)scaleFactor=#endifQStringstr=QString::number(n)if(strlength()==)strprepend("")EnsureitisdoubledigitQFontfontfontsetFamily("Helvetica")intfontHeight=scaleFactor**rectheight()fontsetPixelSize(fontHeight)SetsthefontsizetopixelSizepixelsfontsetBold(true)QPixmappixmap(rectsize()*scaleFactor)pixmapfill(Qt::transparent)QLinearGradientgradient(QPoint(,),QPoint(,pixmapheight()))Constructsalineargradientwithinterpolationareabetween(,)and(,pixmapheight())gradientsetColorAt(,QColor(,,))gradientsetColorAt(,QColor(,,))gradientsetColorAt(,QColor(,,))gradientsetColorAt(,QColor(,,))CreatesstoppointsatthegivenpositionwiththegivencolorQPainterppbegin(pixmap)psetFont(font)QPenpenpensetBrush(QBrush(gradient))SetpenbrushwithlinergridentpsetPen(pen)pdrawText(pixmaprect(),Qt::AlignCenter,str)Drawsthedigitnumber(strhere)withintheprovidedrectanglepend()returnpixmapscaledToWidth(width(),Qt::SmoothTransformation)Returnsascaledcopyoftheimagewhichistransformedusingbilinearfiltering}*preparethepixmap*voidpreparePixmap(){mpixmap=QPixmap(size())mpixmapfill(Qt::transparent)Fillsthepixmapwiththegiventransparentblackvalue(ie,QColor(,,,))QPainterppbegin(mpixmap)pdrawPixmap(,,drawDigits(mnumber,rect()))Drawsthegivendigitspixmapatposition(,)pend()}*definearesizeevent*voidresizeEvent(QResizeEvent*){preparePixmap()update()CausesapaintEvent()call}*Paintthestaticstate*voidpaintStatic(){QPainterp(this)pfillRect(rect(),Qt::black)Fillthewidgetrecwithblackcolorintpad=width()drawFrame(p,rect()adjusted(pad,pad,pad,pad))pdrawPixmap(,,mpixmap)}*Painttheslidestate*voidpaintSlide(){QPainterp(this)pfillRect(rect(),Qt::black)intpad=width()QRectfr=rect()adjusted(pad,pad,pad,pad)drawFrame(p,fr)psetClipRect(fr)setstheclipregiontothegivenrectangleusingthegivenclipoperationinty=height()*manimatorcurrentFrame()pdrawPixmap(,y,mlastPixmap)Drawlasttimestatepixmapfromtoheight()(YCoordinate)insecondpdrawPixmap(,yheight(),mpixmap)Drawcurrenttimestatepixmapfromheight()to(YCoordinate)insecond}*Painttheflipstate*voidpaintFlip(){QPainterp(this)#if!defined(QOSSYMBIAN)!defined(QOSWINCEWM)psetRenderHint(QPainter::SmoothPixmapTransform,true)psetRenderHint(QPainter::Antialiasing,true)#endifpfillRect(rect(),Qt::black)inthw=width()inthh=height()behindisthenewpixmapintpad=width()QRectfr=rect()adjusted(pad,pad,pad,pad)drawFrame(p,fr)pdrawPixmap(,,mpixmap)intindex=manimatorcurrentFrame()if(index<=){thetoppartoftheoldpixmapisflippingintangle=*indexQTransformtransformtransformtranslate(hw,hh)Movesthecoordinatesystemtothecenterofwidgettransformrotate(angle,Qt::XAxis)RotatesthecoordinatesystemcounterclockwisebyangleabouttheXaxispsetTransform(transform)drawFrame(p,fradjusted(hw,hh,hw,hh))pdrawPixmap(hw,hh,mlastPixmap)thebottompartisstilltheoldpixmappresetTransform()psetClipRect(,hh,width(),hh)Enablesclipping,andsetstheclipregiontotherectanglebeginningat(,hh)withthegivenwidthandheightdrawFrame(p,fr)pdrawPixmap(,,mlastPixmap)}else{psetClipRect(,hh,width(),hh)thebottompartisstilltheoldpixmapdrawFrame(p,fr)pdrawPixmap(,,mlastPixmap)thebottompartofthenewpixmapisflippingintangle=*manimatorcurrentFrame()QTransformtransformtransformtranslate(hw,hh)transformrotate(angle,Qt::XAxis)psetTransform(transform)drawFrame(p,fradjusted(hw,hh,hw,hh))pdrawPixmap(hw,hh,mpixmap)}}*Painttherotatestate*voidpaintRotate(){QPainterp(this)intpad=width()QRectfr=rect()adjusted(pad,pad,pad,pad)drawFrame(p,fr)psetClipRect(fr)intangle=*manimatorcurrentFrame()intangle=*manimatorcurrentFrame()intangle=(manimatorcurrentFrame()<=)angle:angleQPixmappix=(manimatorcurrentFrame()<=)mlastPixmap:mpixmapQTransformtransformtransformtranslate(width(),height())transformrotate(angle,Qt::XAxis)psetTransform(transform)psetRenderHint(QPainter::SmoothPixmapTransform,true)pdrawPixmap(width(),height(),pix)}voidpaintEvent(QPaintEvent*event){QUNUSED(event)if(manimatorstate()==QTimeLine::Running){if(mtransition==Slide)paintSlide()if(mtransition==Flip)paintFlip()if(mtransition==Rotate)paintRotate()}else{paintStatic()}}private:intmnumbernumbertosettodigitsintmtransitiontransitionmode(changeeffect)QPixmapmpixmapcurrenttimepixmapQPixmapmlastPixmapnextstatetimepixmapQTimeLinemanimatorusedtoanimateaGUIcontrolbycallingaslotperiodicallyThetimeline'sdurationdescribesforhowlongtheanimationwillrunconnecttheframeChanged()signaltoasuitableslotinthewidgetyouwishtoanimate}classDigiFlip:publicQMainWindow{QOBJECTpublic:DigiFlip(QWidget*parent=):QMainWindow(parent){mhour=newDigits(this)mhour>show()mminute=newDigits(this)mminute>show()QPalettepal=palette()palsetColor(QPalette::Window,Qt::black)Setsthecolorusedforthegivencolorrole,inallcolorgroups,tothespecifiedsolidcolorsetPalette(pal)mtickerstart(,this)SendatimereventeverysecondQTimet=QTime::currentTime()mhour>setNumber(thour())mminute>setNumber(tminute())updateTime()QAction*slideAction=newQAction("Slide",this)QAction*flipAction=newQAction("Flip",this)QAction*rotateAction=newQAction("Rotate",this)connect(slideAction,SIGNAL(triggered()),SLOT(chooseSlide()))connect(flipAction,SIGNAL(triggered()),SLOT(chooseFlip()))connect(rotateAction,SIGNAL(triggered()),SLOT(chooseRotate()))#ifdefined(QOSSYMBIAN)||defined(QOSWINCEWM)menuBar()>addAction(slideAction)menuBar()>addAction(flipAction)menuBar()>addAction(rotateAction)#elseaddAction(slideAction)addAction(flipAction)addAction(rotateAction)setContextMenuPolicy(Qt::ActionsContextMenu)Showsacontextmenu(rightclick)#endif}*Realtimeupdates*voidupdateTime(){QTimet=QTime::currentTime()mhour>flipTo(thour())mminute>flipTo(tminute())QStringstr=ttoString("hh:mm:ss")strprepend(":")if(mhour>transition()==Digits::Slide)strprepend("Slide")if(mhour>transition()==Digits::Flip)strprepend("Flip")if(mhour>transition()==Digits::Rotate)strprepend("Rotate")setWindowTitle(str)}*Switchtransitionmode*voidswitchTransition(intdelta){inti=(mhour>transition()delta)mhour>setTransition(i)mminute>setTransition(i)updateTime()}protected:voidresizeEvent(QResizeEvent*){intdigitsWidth=width()intdigitsHeight=digitsWidth*inty=(height()digitsHeight)mhour>resize(digitsWidth,digitsHeight)mhour>move(,y)mminute>resize(digitsWidth,digitsHeight)mminute>move(width(),y)}*Timerevent,receivetimerevents*voidtimerEvent(QTimerEvent*){updateTime()}*Getkeypressevent*voidkeyPressEvent(QKeyEvent*event){if(event>key()==Qt::KeyRight){switchTransition()event>accept()}if(event>key()==Qt::KeyLeft){switchTransition()event>accept()}}privateslots:voidchooseSlide(){mhour>setTransition()mminute>setTransition()updateTime()}voidchooseFlip(){mhour>setTransition()mminute>setTransition()updateTime()}voidchooseRotate(){mhour>setTransition()mminute>setTransition()updateTime()}private:QBasicTimermtickerDigits*mhourDigits*mminute}#include"digiflipmoc"intmain(intargc,char*argv){QApplicationapp(argc,argv)DigiFliptime#ifdefined(QOSSYMBIAN)||defined(QOSWINCEWM)timeshowFullScreen()#elsetimeresize(,)timeshow()#endifreturnappexec()}.QT中线程的使用。QThread的用法其实比较简单只需要派生一个QThread的子类实现其中的run虚函数就大功告成用的时候创建该类的实例调用它的start方法即可。但是run函数使用时有一点需要注意即在其中不能创建任何gui线程(诸如新建一个QWidget或者QDialog)。如果要想通过新建的线程实现一个gui的功能那么就需要通过使用线程间的通信来实现。这里使用一个简单的例子来理解一下QThread中signalslot的相关用法。首先派生一个QThread的子类MyThreadhviewplaincopytoclipboardprintclassMyThread:publicQThread{QOBJECTpublic:MyThread()voidrun()signals:voidsend(QStrings)}classMyThread:publicQThread{QOBJECTpublic:MyThread()voidrun()signals:voidsend(QStrings)}voidsend(QStrings)就是定义的信号MyThreadcppviewplaincopytoclipboardprint#include"MyThreadh"MyThread::MyThread(){}voidMyThread::run(){while(true){sleep()emitsend("Thisisthesonthread")qDebug()<<"Threadisrunning!"}exec()}#include"MyThreadh"MyThread::MyThread(){}voidMyThread::run(){while(true){sleep()emitsend("Thisisthesonthread")qDebug()<<"Threadisrunning!"}exec()}emitsend("Thisisthesonthread")为发射此信号在run中循环发送每次休眠五秒之后我们需要在另外的线程中定义一个slot来接受MyThread发出的信号。如新建一个MyWidgetMyWidgethviewplaincopytoclipboardprintclassMyWidget:publicQWidget{QOBJECTpublic:MyWidget(QWidget*parent=)~Widget()publicslots:voidreceiveslot(QStrings)}classMyWidget:publicQWidget{QOBJECTpublic:MyWidget(QWidget*parent=)~Widget()publicslots:voidreceiveslot(QStrings)}voidreceiveslot(QStrings)就用来接受发出的信号并且实现参数的传递。MyWidgetcppviewplaincopytoclipboardprint#include"MyWidgeth"MyWidget::MyWidget(QWidget*parent):QWidget(parent){}MyWidget::~MyWidget(){}voidMyWidget::receiveslot(QStrings){QMessageBox::information(,"Information",s)}#include"MyWidgeth"MyWidget::MyWidget(QWidget*parent):QWidget(parent){}MyWidget::~MyWidget(){}voidMyWidget::receiveslot(QStrings){QMessageBox::information(,"Information",s)}接受函数实现弹出发送信号中所含参数(QString类型)的消息框在main()函数中创建新线程来实现两个线程间的交互。maincppviewplaincopytoclipboardprint#include<QtGui>#include"MyWidgeth"intmain(intargc,char*argv){QApplicationa(argc,argv)MyWidgetwwshow()MyThread*mth=newMyThreadQObject::connect(mth,SIGNAL(send(QString)),w,SLOT(receiveslot(QString)))mth>start()returnaexec()}#include<QtGui>#include"MyWidgeth"intmain(intargc,char*argv){QApplicationa(argc,argv)MyWidgetwwshow()MyThread*mth=newMyThreadQObject::connect(mth,SIGNAL(send(QString)),w,SLOT(receiveslot(QString)))mth>start()returnaexec()}制作冒泡式弹出对话框制作冒泡式弹出对话框主要涉及个技术要点(主要供触摸屏使用)实用的Qtimer类的使用(计算鼠标在对象上的停留时间确定是否弹出属性对话框)漂亮的对话框的绘制(主要是QWidget::setMask(constQBitmapbitmap)的使用)详细分析:QTimer类的使用QTimer的一般性使用QTimer*timer=newQTimer(myObject)   connect(timer,SIGNAL(timeout()),            myObject,SLOT(timerDone()))timer>start(,TRUE)                secondssingleshot注意:当myObject销毁时Qtimer会自动销毁。不需要手工删除。        QTimer的intstart(intmsec,boolsshot=FALSE)方法第二个参数sshot如果为ture则myObject的槽方法只会执行一次。不然的话会一直执行直到QTimer停止或者对象被销毁为止。在本程序中如何使用QTimer类头文件classMainPanel:publicQWidget{                MainPanel为被测试面板测试弹出属性框        QOBJECTpublic:        MainPanel(QWidget*parent=,constchar*name=,WFlagsfl=)        ~MainPanel(){}publicslots:        voidholdMouseToPopupDialog()           供QTimer链接的槽确定是否弹出属性框protected:        virtualvoidmousePressEvent(QMouseEvent*)   这三个虚函数需要被覆盖用作计时        virtualvoidmouseReleaseEvent(QMouseEvent*)        virtualvoidmouseMoveEvent(QMouseEvent*)private:        QPoint*popupPoint                    弹出面板的坐标也就是要显示属性的物体        PopupInfoDialog*propDialog               这个属性框的制作放到后面        QTimer*mouseHoldClicker                创建一个Qtimer类成员对象}代码文件MainPanel::MainPanel(QWidget*parent,constchar*name,WFlagsfl):QWidget(parent,name,fl){        propDialog=newPopupInfoDialog(,,this,,,QDialog::WStyleCustomize|QDialog::WStyleNoBorder|QDialog::WStyleStaysOnTop)        mouseHoldClicker=newQTimer(this)                           popupPoint=newQPoint()                                                     创建一个默认弹出点        connect(mouseHoldClicker,SIGNAL(timeout()),this,SLOT(holdMouseToPopupDialog()))  链接QTimer和面板}voidMainPanel::mousePressEvent(QMouseEvent*e){    这个方法的意思是如果当鼠标按下(触摸屏的话就是手指按下)        popupPoint>setX(e>x())                              保存当前的坐标点        popupPoint>setY(e>y())        propDialog>hide()                                   隐藏以前出现的弹出式属性框        mouseHoldClicker>start(,true)                    以秒计时如果手指没有离开这个点或者没有移动则                                                         触发holdMouseToPopupDialog()槽一次。}voidMainPanel::mouseReleaseEvent(QMouseEvent*e){         这个方法的意思是如果手指离开触摸屏就。。。        mouseHoldClicker>stop()                  如果在槽还没有触发前就停止计时器这样不用弹出属性框了}voidMainPanel::mouseMoveEvent(QMouseEvent*e){           这个方法的意思是如果手指移动了的话就。。。。。。。。        if(e>x()popupPoint>x()>||e>y()popupPoint>y()>){如果手指在个像素内移动就认为可接受的如果超过个                  mouseHoldClicker>stop()                          像素则不予弹出对话框        }}voidMainPanel::holdMouseToPopupDialog(){                   测试面板的槽用来弹出属性框        propDialog>popupAtPoint(popupPoint>x(),popupPoint>y())        propDialog>show()}在本程序中绘制漂亮的对话框classPopupInfoDialog:publicQDialog{        QOBJECTpublic:        PopupInfoDialog(intareaWidth=,intareaHeight=,QWidget*parent=,constchar*name=,boolmodal=FALSE,WFlagsf=)        voidpopupAtPoint(intx,inty)private:        voidrefreshMask(intpopX,intpopY)                       重新刷新蒙板隐藏对话框该的一些不需要显示的地方。        voidfillArrow(QPainter,int,int,int,int,int,int)                  这个是画这个东东的àvoidPopupInfoDialog::popupAtPoint(intx,inty){                  对话框就弹出在这个点在测试面板的            holdMouseToPopupDialog()中调用此方法。        this>refreshMask(x,y)        this>show()}*在这里大致的实现过程是这样QWidget可以通过一个QBitmap蒙板来大致决定需要显示哪些部分我们就通过绘制蒙板来让QWidget显示蒙板同样大小区域来实现绘制任意形状的对话框的效果*voidPopupInfoDialog::refreshMask(intpopX,intpopY){           重新刷新蒙板        QBitmapmask(PopupWidth,PopupHeight,true)            创建一个蒙板        QPainterpainter(mask)                                           paintersetPen(popupBorder)        paintersetBrush(blackBrush)                                必须设置笔刷得把绘制区域全部填充满        painterdrawRoundRect(,,,,,)是实际显示内容框为圆角矩形圆角半径        intdistanceToBorder        if(areaWidthpopX>=PopupWidth){右边能容纳弹出框这是一个简单的算法在对象右边能显示对话框就在右边                  if(popY<=areaHeight){三角符号在弹出框的上边            绘制属性对话框不然就在左边绘制属性对话框。                           if(popY<=DialogToBorderDistance){                                    distanceToBorder=popY                           }else{                                    distanceToBorder=DialogToBorderDistance                           }                           fillArrow(painter,,popYdistanceToBorder,,,,)                           this>move(popX,distanceToBorder)                  }else{三角符号在弹出框的下边                           intdx=popX                           intdy=areaHeightPopupHeightDialogToBorderDistance                           if((areaHeightpopY)<=DialogToBorderDistance){                                    dy=areaHeightPopupHeight(areaHeightpopY)                           }                           fillArrow(painter,,popY(dy),,,,)                           this>move(dx,dy)                  }        }else{弹出框放在左边                  if(popY<=areaHeight){三角符号在弹出框的上边                           if(popY<=DialogToBorderDistance){                                    distanceToBorder=popY                           }else{                                    distanceToBorder=DialogToBorderDistance                           }                           fillArrow(painter,PopupWidth,popYdistanceToBorder,PopupWidth,,PopupWidt

用户评论(0)

0/200

精彩专题

上传我的资料

每篇奖励 +2积分

资料评价:

/38
1下载券 下载 加入VIP, 送下载券

意见
反馈

立即扫码关注

爱问共享资料微信公众号

返回
顶部