【发布时间】:2015-10-28 11:34:17
【问题描述】:
我试图理解为什么下面的代码在子类之后使用一个冒号。我尝试在网上搜索,但没有得到有关其原因的信息。
myLabel.h 文件
#ifndef MYLABEL_H
#define MYLABEL_H
#include <QApplication>
#include <QMainWindow>
#include <QHBoxLayout>
#include <QLabel>
#include <QMouseEvent>
class MyLabel : public QLabel
{
Q_OBJECT
public:
explicit MyLabel(QWidget *parent = 0);
~MyLabel(){}
protected:
void mouseMoveEvent ( QMouseEvent * event );
};
#endif // MYLABEL_H
myLabel.cpp 文件
#include "mylabel.h"
#include "ui_mainwindow.h"
MyLabel::MyLabel(QWidget *parent) : QLabel(parent) //QWidget calls the widget, QLabel calls text
{
this->setAlignment(Qt::AlignCenter);
//Default Label Value
this->setText("No Value");
//set MouseTracking true to capture mouse event even its key is not pressed
this->setMouseTracking(true);
}
main.cpp
//#include "mainwindow.h"
#include "mylabel.h"
#include "rectangle.h"
#include <QApplication>
#include <QHBoxLayout>
#include <QPainterPath>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QMainWindow *window = new QMainWindow();
window->setWindowTitle(QString::fromUtf8("QT - Capture Mouse Move"));
window->resize(500, 450);
QWidget *centralWidget = new QWidget(window);
QHBoxLayout* layout = new QHBoxLayout(centralWidget);
MyLabel* CoordinateLabel = new MyLabel();
layout->addWidget(CoordinateLabel);
window->setCentralWidget(centralWidget);
window->show();
return app.exec();
}
void MyLabel::mouseMoveEvent( QMouseEvent * event )
{
// Show x and y coordinate values of mouse cursor here
QString txt = QString("X:%1 -- Y:%2").arg(event->x()).arg(event->y());
setText(txt);
}
另外,有人可以解释一下 myLabel.cpp 文件中引用的指针“this”是什么吗?
谢谢大家
【问题讨论】:
-
哪个冒号让您感到困惑:类定义中的冒号 (
class A : public B),还是构造函数中的冒号 (A::A() : B())? -
@JLREng 我相信在研究 Qt 程序之前,你应该首先阅读至少一本关于 C++ 的书。:)
-
有人能解释一下“this”引用的指针是什么吗:问 Scott Meyers。
-
@singerofthefall 类定义。我对构造函数很清楚,但我对定义感到困惑。
-
这里没有解释为什么使用冒号。这只是一个随意的规则。假设,C++ 可以被定义为允许
class A public B。