二、QML,C++方法相互调用
  新建类:
//numbercount.h
#ifndef NumberCount_H
#define NumberCount_H
#include <QObject>
#include <QVariant>
class NumberCount : public QObject
{
Q_OBJECT
public:
explicit NumberCount(QObject *parent = 0);
Q_INVOKABLE int getTotal();
signals:
void resetData(QVariant num);//用于调用qml的javascript 方法
public slots:
int incre();
int decre();
void reset(int num);
private:
int count;
int total;
};
#endif // NumberCount_H
//==========================================================
//NumberCount.cpp
#include "numbercount.h"
#include <QDebug>
NumberCount::NumberCount(QObject *parent) :
QObject(parent)
{
this->total = 100;
}
int NumberCount::incre()
{
qDebug()<<"count=: "<< ++total;
count++;
return count;
}
int NumberCount::decre()
{
qDebug()<<"count=: "<< --total;
count--;
return count;
}
void NumberCount::reset(int num)
{
this->total = num;
count = 0;
emit resetData(QVariant(num));//调用qml的javascript 方法
}
int NumberCount::getTotal()
{
return total;
}
//==========================================================
//numbercount.qml
import Qt 4.7
Rectangle {
//signal resetData;
function resetData(text){
console.log("javascript resetData方法被C++调用!");
btn_decre.text =  "增加<font color='#0000FF'>(0)</font>";
btn_incre.text = "减少<font color='#0000FF'>(0)</font>";
txt_show.text = "总数:" + text;
txt_reset.text = "总数重置为:"+text;
}
width: 300
height: 300
radius: 20
anchors.fill: parent
Text {
id: txt_show
x: 150
y: 0
text : "总数:" + numberCount.getTotal(100);
}
Rectangle{
x:100
y:50
width: 80
height: 25
Image{
anchors.fill: parent
width:parent.width
height: parent.width
source: "/ui/images/button.png"
}
Text {
id: btn_incre
anchors.centerIn: parent
text: "增加"
MouseArea{
anchors.fill: parent
onClicked: {
var num = numberCount.incre();
parent.text =  "增加<font color='#0000FF'>(" + num +")</font>";
btn_decre.text = "减少<font color='#0000FF'>("+ num+")</font>";
txt_show.text = "总数:" + numberCount.getTotal();
}
}
}
}
Rectangle{
x:100
y:100
width: 80
height: 25
Image{
anchors.fill: parent
width:parent.width
height: parent.width
source: "/ui/images/button.png"
}
Text {
id: btn_decre
anchors.centerIn: parent
text: "减少"
MouseArea{
anchors.fill: parent
onClicked: {
var num = numberCount.decre();
parent.text =  "减少<font color='#0000FF'>(" + num +")</font>";
btn_incre.text = "增加<font color='#0000FF'>("+ num+")</font>";
txt_show.text = "总数:" + numberCount.getTotal();
}
}
}
}
Rectangle{
x:100
y:150
width: 80
height: 25
Image{
anchors.fill: parent
width:parent.width
height: parent.width
source: "/ui/images/button.png"
}
Text {
id: btn_show
anchors.centerIn: parent
text: "重置总数"
MouseArea{
anchors.fill: parent
onClicked: {
numberCount.reset(200);
}
}
}
}
Text {
id: txt_reset
x: 100
y: 200
color: "#12ff12"
}