一说起函数重载,大多数人都会想起c++或者Java中的函数重载,函数重载,其实就是同名函数,不同形参列表的应用,一方面是为了语法便利,另一方面是面对对象的思维表现
在Qt中,使用qmlRegisterType函数注册一个新的qml类型到qml的运行环境中去,那么在调用的时候,就可以像在c++中那样调用一个重载函数
例如:
运行结果:
在Qt中,使用qmlRegisterType函数注册一个新的qml类型到qml的运行环境中去,那么在调用的时候,就可以像在c++中那样调用一个重载函数
例如:
向qml注册一个QObject的子类,这个类重载了test函数
OverLoadedFunction.h
#ifndef OVERLOADEDFUNCTION_H
#define OVERLOADEDFUNCTION_H
#include <QObject>
#include <QDebug>
#include <QString>
class OverLoadedFunction : public QObject
{
Q_OBJECT
public:
explicit OverLoadedFunction(QObject *parent = 0);
Q_INVOKABLE void test(){
qDebug()<<"arguments list is null";
}
Q_INVOKABLE void test(int num){
qDebug()<<"arguments list is int"<<num;
}
Q_INVOKABLE void test(double dnum){
qDebug()<<"arguments list is double"<<dnum;
}
Q_INVOKABLE void test(QString string){
qDebug()<<"arguments list is string"<<string;
}
Q_INVOKABLE void test(int num,double dnum){
qDebug()<<"arguments list is int && double"<<num<<"&&"<<dnum;
}
Q_INVOKABLE void test(double dnum,int num){
qDebug()<<"arguments list is double && int"<<dnum<<"&&"<<num;
}
};
#endif // OVERLOADEDFUNCTION_H
main.c
#include <QtGui/QApplication>
#include "qmlapplicationviewer.h"
#include "overloadedfunction.h"
#include <QtDeclarative>
Q_DECL_EXPORT int main(int argc, char *argv[])
{
QScopedPointer<QApplication> app(createApplication(argc, argv));
OverLoadedFunction over;
QmlApplicationViewer viewer;
viewer.setOrientation(QmlApplicationViewer::ScreenOrientationAuto);
qmlRegisterType<OverLoadedFunction>("com.OverLoadedFunction",1,0,"OverLoadedFunction");
over.test(1);
viewer.setMainQmlFile(QLatin1String("qml/Overloaded/main.qml"));
viewer.showExpanded();
return app->exec();
}
main.qml
// import QtQuick 1.0 // to target S60 5th Edition or Maemo 5
import QtQuick 1.1
import com.OverLoadedFunction 1.0
Rectangle {
width: 360
height: 360
Text {
text: qsTr("Hello World")
anchors.centerIn: parent
}
MouseArea {
anchors.fill: parent
onClicked: {
overload.test();
overload.test(1);
overload.test(1,1.0);
overload.test(1.0,1);
overload.test("string");
}
}
OverLoadedFunction{
id:overload
}
}
运行结果:
E:\Qt\QtQuick_C++\Overloaded-build-desktop-Qt_4_8_1_for_Desktop_-_MinGW__Qt_SDK____\debug\Overloaded.exe 启动中...
arguments list is int 1
Qml debugging is enabled. Only use this in a safe environment!
arguments list is null
arguments list is double 1
arguments list is double && int 1 && 1
arguments list is double && int 1 && 1
arguments list is string "string"
而在qml中,在传递形参前却发生了先进行类型转换在传递的行为。