分类: C/C++
2014-07-21 21:45:31
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QDeclarativeView view;
view.rootContext()->setContextProperty("ls",new LS);
view.setSource(QUrl::fromLocalFile("../QMLAPP/QMLtest.qml"));
view.show();
return app.exec();
}// LS.h
#define LS_H
#include
#include
class LS : public QObject
{
Q_OBJECT
Q_PROPERTY(QColor color READ getColor WRITE setColor NOTIFY colorChange)
public:
LS(QObject *parent = 0);
~LS();
// Q_INVOKABLE 用于导出函数,让qml能使用
Q_INVOKABLE QString getText(void) const;
// 用于属性
QColor getColor(void) const;
void setColor(const QColor &c);
signals:
void sendMsg(const QString &s);
// 用于属性
void colorChange(void);
public slots:
void echoMsg(const QString &s);
private:
QString m_str;
QColor m_Color;
};
#endif // LS_H
//LS.cpp#include "LS.h"
LS::LS(QObject *parent)
:QObject(parent),m_str("I am LS class"),m_Color(Qt::blue)
{
QObject::connect(this, SIGNAL(sendMsg(QString)), this, SLOT(echoMsg(QString)));
}
LS::~LS(){}
QString LS::getText(void) const
{
return m_str;
}
// 用于属性
QColor LS::getColor(void) const
{
return m_Color;
}
void LS::setColor(const QColor &c)
{
m_Color = c;
}
void LS::echoMsg(const QString &s)
{
qDebug(" %s ", s.toLocal8Bit().data());
}
//---------------------------------------------------------------------- // QMLtest.qml Rectangle{ id: mainrect width: 400; height: 300; color: ls.color; Text { id: tls; text: "click this" } MouseArea{ anchors.fill: parent; onClicked: { tls.text = ls.getText(); ls.sendMsg(" ok "); } } }