Created
April 15, 2019 07:50
-
-
Save lixingcong/3ed8890b08c474360a6eb3fcacd31e3c to your computer and use it in GitHub Desktop.
qt5的Q_D宏和Q_Q宏封装pimp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "Label.h" | |
#include "Label_p.h" | |
Label::Label(const QString& text, QWidget *parent) : QLabel(text, parent), | |
d_ptr(new LabelPrivate(this)) | |
{ | |
} | |
QString Label::myGetText() | |
{ | |
Q_D(const Label); // Q_D宏仅在API所在的类访问Private类 | |
return d->string; | |
} | |
void Label::mySetText(const QString& string) | |
{ | |
Q_D(Label); // Q_D宏仅在API所在的类访问Private类 | |
d->setMyText(string); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef LABEL_H | |
#define LABEL_H | |
#include <QLabel> | |
class LabelPrivate; | |
class Label : public QLabel | |
{ | |
Q_OBJECT | |
Q_DECLARE_PRIVATE(Label) | |
public: | |
explicit Label(const QString& text, QWidget *parent = nullptr); | |
~Label(){} // 必须声明为非inline,否则QScopedPointer无法被析构 | |
QString myGetText(); | |
void mySetText(const QString& string); | |
private: | |
QScopedPointer<LabelPrivate> d_ptr; | |
}; | |
#endif // LABEL_H |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef LABEL_P_H | |
#define LABEL_P_H | |
#include "Label.h" | |
class LabelPrivate | |
{ | |
Q_DECLARE_PUBLIC(Label) | |
public: | |
LabelPrivate(Label* parent): q_ptr(parent) | |
{ | |
string="LabelPrivate"; | |
} | |
void setMyText(const QString& text) | |
{ | |
Q_Q(Label); // Q_Q宏仅在Private类访问API所在的类 | |
q->setText(text); | |
} | |
QString string; | |
private: | |
Label* const q_ptr; | |
}; | |
#endif // LABEL_P_H |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment