<center><h1>Press: (%1 , %2)</h1></center>表示的是在中间,<h1>表示的是字体
<h1>.......</h1>表示h1字体在中间范围内即(......)中的内容。
这里是表示鼠标按键的事件
代码如下:
#include <QApplication> #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 a(argc, argv); EventLabel *label = new EventLabel; label->setWindowTitle("MouseEvent Demo"); label->resize(300,200); label->setMouseTracking(true); label->show(); return a.exec(); }
代码如下:
//custombutton.h #include <QPushButton> #include <QDebug> #include <QMouseEvent> class CustomButton : public QPushButton { Q_OBJECT public: CustomButton(QWidget *parent = 0); protected: void mousePressEvent(QMouseEvent *event); private: void onButtonCliecked(); }; //custombutton.cpp #include "custombuttom.h" CustomButton::CustomButton(QWidget *parent ) : QPushButton(parent) { connect(this, &CustomButton::clicked, this, &CustomButton::onButtonCliecked); } void CustomButton::onButtonCliecked() { qDebug()<<"You clicked this!"; } void CustomButton::mousePressEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) { qDebug()<<"left"; } else { QPushButton::mousePressEvent(event); } } //main.cpp #include <QApplication> #include "custombuttom.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); CustomButton btn; btn.setText("This is a Button!"); btn.show(); return a.exec(); }
如果想忽略事件,只需要调用父类的响应函数即可。