接下来说说QT的响应事件吧,做过开发的应该都知道,无论是在做什么都离不开这个事件---event。好吧,今天说一说QT的事件监听是怎么实现的。先来看看一段代码吧:
#include <QApplication>
#include <QWidget>
#include <QLabel>
#include <QMouseEvent>
class EventLabel : public QLabel
{
protected:
void mouseMoveEvent(QMouseEvent *event); //申明三个事件函数
void mousePressEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
};
void EventLabel::mouseMoveEvent(QMouseEvent *event) //实现鼠标移动事件函数,显示出鼠标的坐标
{
this->setText(QString("<center><h1>Move: (%1, %2)</h1></center>")
.arg(QString::number(event->x()), QString::number(event->y())));
}
void EventLabel::mousePressEvent(QMouseEvent *event) //同上
{
this->setText(QString("<center><h1>Press: (%1, %2)</h1></center>")
.arg(QString::number(event->x()), QString::number(event->y())));
}
void EventLabel::mouseReleaseEvent(QMouseEvent *event) //同上,只是实现的形式变了一下,不过用上面的方法一样能实现
{
QString msg;
msg.sprintf("<center><h1>Release: (%d, %d)</h1></center>",
event->x(), event->y());
this->setText(msg);
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
EventLabel *label = new EventLabel;
label->setWindowTitle("MouseEvent Demo");
label->resize(300, 200);
label->show();
return app.exec();
}
运行效果如下:
大家可以看到,里面有html的标签代码,可见QT还是挺强大的,有了这些东西的结合,QT的内容更加丰富了。所以大家多掌握一些东西是挺重要的!