Skip to content

Instantly share code, notes, and snippets.

@lixingcong
Created Apr 15, 2019
Embed
What would you like to do?
qt5的Q_D宏和Q_Q宏封装pimp
#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);
}
#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
#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