Posted on 2011-08-04 21:19
RTY 閱讀(818)
評論(0) 編輯 收藏 引用 所屬分類:
Qt 、
轉載隨筆 、
QML
廢話不多說直接上代碼
((xp下qt4.7 sdk) 出現情況是,當一個類在直接寫在一個.h文件上后,在QML中調用會掛掉,我這里出現是在我調用的到處函數是獲取一個QString的時候,但是把類分別寫成.h和.cpp后,沒有出現此 情況,不知道具體的原因)
// main.cpp 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
#ifndef LS_H#define LS_H
#include <QObject>
#include <QColor>
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 ");
}
}
}