实验:
1)用Time显示时间
2)用Timer定时
3)鼠标左键按下控件可随意在桌面上拖动
main.cpp
#include <qapplication.h>
#include "form2.h"
int main( int argc, char ** argv )
{
QApplication a( argc, argv );
Form2 w;
w.show();
a.connect( &a, SIGNAL( lastWindowClosed() ), &a, SLOT( quit() ) );
return a.exec();
}
form2.cpp
/****************************************************************************
** Form implementation generated from reading ui file 'form2.ui'
**
** Created by: The User Interface Compiler ($Id: qt/main.cpp 3.3.6 edited Aug 31 2005 $)
**
** WARNING! All changes made in this file will be lost!
****************************************************************************/
#include "form2.h"
#include <qvariant.h>
#include <qlcdnumber.h>
#include <qlayout.h>
#include <qtooltip.h>
#include <qwhatsthis.h>
#include <qimage.h>
#include <qpixmap.h>
#include<qtimer.h>
#include<qdatetime.h>
#include <qpoint.h>
/*
* Constructs a Form2 as a child of 'parent', with the
* name 'name' and widget flags set to 'f'.
*
* The dialog will by default be modeless, unless you set 'modal' to
* TRUE to construct a modal dialog.
*/
DigiClock::DigiClock(QWidget * parent, const char * name)
: QLCDNumber(parent,name)
{
QPalette p = palette();
p.setColor(QPalette::Normal, QColorGroup::Background, Qt::blue);
setPalette(p);
QTimer *timer = new QTimer(this);
connect(timer,SIGNAL(timeout()),SLOT(showTime()));
timer->start(1000);
showColon = true;
showTime();
}
void DigiClock::showTime()
{
QTime time = QTime::currentTime();
QString text = time.toString("hh:mm");
if(showColon)
{
text[2] = ':';
showColon = false;
}
else
{
text[2] = ' ';
showColon = true;
}
display(text);
}
Form2::Form2( QWidget* parent, const char* name, bool modal, WFlags fl )
: QDialog( parent, name, modal, fl )
{ setMouseTracking (true);
if ( !name )
setName( "Form2" );
lCDNumber2 = new DigiClock( this, "lCDNumber2");
lCDNumber2->setGeometry( QRect( 0, 0, 370, 70 ) );
languageChange();
resize( QSize(369, 70).expandedTo(minimumSizeHint()) );
clearWState( WState_Polished );
LbuttonFlag = false;
}
/*
* Destroys the object and frees any allocated resources
*/
Form2::~Form2()
{
// no need to delete child widgets, Qt does it all for us
}
/*
* Sets the strings of the subwidgets using the current
* language.
*/
void Form2::languageChange()
{
setCaption( tr( "Form2" ) );
}
void Form2::mousePressEvent(QMouseEvent *e)
{
if(e->button()==QMouseEvent::LeftButton)
{
dragPositon = e->globalPos()-frameGeometry().topLeft();
LbuttonFlag = true;
e->accept();
}
}
void Form2::mouseReleaseEvent(QMouseEvent * e)
{
LbuttonFlag = false;
}
void Form2::mouseMoveEvent(QMouseEvent *e)
{
if(LbuttonFlag)
{
move(e->globalPos()-dragPositon);
qDebug("gx=%d,gy%d,x=%d,y=%d",e->globalX(),e->globalY(),dragPositon.x(),dragPositon.y());
e->accept();
}
}