关于QML中调用qt类中的信号,槽,成员函数,属性做记录


废话不多说直接上代码

( (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 ");
}
}

}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值