事件
事件是对各种应用程序需要知道的由应用程序内部或者外部产生的事情或者动作的通称。对于初学者,总会对Qt中信号和事件的概念混淆不清。其实,记住事件比信号更底层就可以了。比如说,我们用鼠标按下界面上的一个按钮,它会发射clicked()单击信号,但是,它怎么知道自己被按下的呢,那就是通过鼠标事件处理的。这里可以看到,鼠标事件比信号更底层
在Qt中处理事件有多种方法,不过最常用的是重写Qt事件处理函数
鼠标事件、键盘事件
新建Qt Gui应用,项目名称为“myEvent”,基类更改为QWidget,类名为Widget
向ui界面拖入一个按钮
实现当鼠标在界面上点击时,按钮就会显示出当前鼠标的坐标值
实现W、S、A、D移动按钮
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QMouseEvent>
#include <QKeyEvent>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
protected:
void mousePressEvent(QMouseEvent *);
void keyPressEvent(QKeyEvent *);
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
}
Widget::~Widget()
{
delete ui;
}
void Widget::mousePressEvent(QMouseEvent *e)
{
ui->pushButton->setText(tr("(%1, %2)").arg(e->x()).arg(e->y()));
}
void Widget::keyPressEvent(QKeyEvent *e)
{
int x = ui->pushButton->x();
int y = ui->pushButton->y();
switch(e->key())
{
case Qt::Key_W : ui->pushButton->move(x, y-10); break;
case Qt::Key_S : ui->pushButton->move(x, y+10); break;
case Qt::Key_A : ui->pushButton->move(x-10, y); break;
case Qt::Key_D : ui->pushButton->move(x+10, y); break;
}
}
除了鼠标按下事件,还有鼠标释放、双击、移动、滚轮等事件
定时器事件
新建Qt Gui应用,项目名称为myTimer,基类选择QWidget,类名为Widget
在ui界面拖入两个label
设置三个定时器,分别返回他们的id,执行不同的操作
widget.h
protected:
void timerEvent(QTimerEvent *);
private:
int id1, id2, id3;
widget.cpp
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
id1 = startTimer(1000);
id2 = startTimer(2000);
id3 = startTimer(10000);
}
void Widget::timerEvent(QTimerEvent *e)
{
if(e->timerId() == id1)
{
ui->label->setText(tr("%1").arg(qrand()%10));
}
else if(e->timerId() == id2)
{
ui->label_2->setText(tr("hello"));
}
else
{
qApp->quit();
}
}
定时器
开启少量定时器,也可以通过信号槽实现
在ui界面添加一个QLineEdit
widget.h
private slots:
void timerUpdate();
widget.cpp
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(timerUpdate()));
timer->start(1000);
}
void Widget::timerUpdate()
{
QDateTime time = QDateTime::currentDateTime();
QString str = time.toString("yyyy-MM-dd hh:mm:ss dddd");
ui->lineEdit->setText(str);
}
随机数
Qt中是使用qrand()和qsrand()两个函数实现的。在前面的程序中已经看到了qrand()函数的使用,其可以产生随机数,qrand()%10可以产生0-9之间的随机数。要想产生100以内的随机数就是%100
在使用qrand()函数产生随机数之前,一般要使用qsrand()函数为其设置初值,如果不设置初值,那么每次运行程序,qrand()都会产生相同的一组随机数。为了每次运行程序时,都可以产生不同的随机数,我们要使用qsrand()设置一个不同的初值。这里使用了QTime类的secsTo()函数,它表示两个时间点之间所包含的秒数,比如代码中就是指从零点整到当前时间所经过的秒数
widget.cpp
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
qsrand(QTime(0, 0, 0).secsTo(QTime::currentTime()));
}
void Widget::timerUpdate()
{
int rand = qrand() % 300;
ui->lineEdit->move(rand, rand);
}