qt下qml和c++交互信号槽机制测试

qt下qml和c++交互信号槽机制测试

本文博客链接:,作者:jdh,转载请注明.

环境:

主机:WIN7

开发环境:Qt5.2

说明:

写一个测试程序测试qml和c++利用信号槽机制传输信息.

测试程序功能:16进制和10进制互相转换.

源代码:

main.cpp

#include <QtGui/QGuiApplication>#include "qtquick2applicationviewer.h"#include <QtQml/QQmlContext>#include <QtQuick/QQuickItem>#include <QtQuick/QQuickView>#include "myclass.h"int main(int argc, char *argv[]){QGuiApplication app(argc, argv);MyClass my;QtQuick2ApplicationViewer viewer;viewer.setMainQmlFile(QStringLiteral("qml/Hex2Dec/main.qml"));QQuickItem *rootObject = viewer.rootObject();rootObject->setProperty("fileName", "jdh");QObject::connect(rootObject,SIGNAL(btn_2dec_click(QString)),\&;my,SLOT(slot_hex2dec(QString)));QObject::connect(rootObject,SIGNAL(btn_2hex_click(QString)),\&;my,SLOT(slot_dec2hex(QString)));QObject::connect(&my,SIGNAL(sig_disp(QVariant)),\rootObject,SLOT(disp(QVariant)));//viewer.showExpanded();viewer.showFullScreen();rootObject->setProperty("str_out","0x");return app.exec();}myclass.h#ifndef MYCLASS_H#define MYCLASS_H#include <QObject>#include <QDebug>class MyClass : public QObject{Q_OBJECTpublic:explicit MyClass(QObject *parent = 0);signals:void sig_disp(QVariant str_num);public slots:void slot_hex2dec(QString str_num);void slot_dec2hex(QString str_num);};#endif // MYCLASS_Hmyclass.cpp#include "myclass.h"#include <QtGui/QGuiApplication>#include "qtquick2applicationviewer.h"#include <QtQml/QQmlContext>#include <QtQuick/QQuickItem>#include <QtQuick/QQuickView>MyClass::MyClass(QObject *parent) :QObject(parent){}//十六进制转十进制void MyClass::slot_hex2dec(QString str_num){qDebug() << "11" << str_num;bool ok;emit sig_disp("dec:" + QString::number(str_num.toInt(&ok,16),10));}//十进制转十六进制void MyClass::slot_dec2hex(QString str_num){qDebug() << "22" << str_num;bool ok;emit sig_disp("hex:0x" + QString::number(str_num.toInt(&ok,10),16));}main.qmlimport QtQuick 2.0import QtQuick.Controls 1.1import QtQuick.Layouts 1.0Rectangle {id : rect//按键按下发射signal btn_2dec_click(string str_num)signal btn_2hex_click(string str_num)width: 360height: 360ColumnLayout {id: columnLayout1x: 8y: 15width: 310height: 324Label {id: label2x: 83y: -37width: 178height: 12text: "十六进制和十进制转换器 by jdh"}RowLayout {id: rowLayout1x: 0y: -216width: 310height: 50spacing: 1Label {id: label1x: 0y: -199width: 57height: 39text: "输入:"}TextField {id: txt_inx: 71y: -204width: 254height: 39placeholderText: qsTr("Text Field")}}RowLayout {id: rowLayout2x: 0y: -153width: 310height: 50Label {id: label3x: 13y: -151width: 57height: 39text: "输出:"}TextField {id: txt_outx: 76y: -151width: 254height: 39placeholderText: qsTr("Text Field")}}RowLayout {id: rowLayout3x: 0y: -80width: 310height: 50Button {id: btn_2decx: 13y: -75width: 108height: 44text: "转十进制"onClicked: btn_2dec_click(txt_in.text)}Button {id: btn_2hexx: 222y: -75width: 108height: 44text: "转十六进制"onClicked: btn_2hex_click(txt_in.text)}}}function disp(str_num){txt_out.text = str_num}}运行效果:

,昨晚多几分钟的准备,今天少几小时的麻烦。

qt下qml和c++交互信号槽机制测试

相关文章:

你感兴趣的文章:

标签云: