本文共 4268 字,大约阅读时间需要 14 分钟。
qt下qml和c++交互信号槽机制测试
本文博客链接:,作者:jdh,转载请注明.
环境:
主机:WIN7
开发环境:Qt5.2
说明:
写一个测试程序测试qml和c++利用信号槽机制传输信息.
测试程序功能:16进制和10进制互相转换.
源代码:
main.cpp
#includemyclass.h#include "qtquick2applicationviewer.h"#include #include #include #include "myclass.h"int main(int argc, char *argv[]){ QGuiApplication app(argc, argv); MyClass my; QtQuick2ApplicationViewer viewer; viewer.setMainQmlFile(QStringLiteral("qml/Hex2/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();}
#ifndef MYCLASS_H#define MYCLASS_H#includemyclass.cpp#include 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_H
#include "myclass.h"#includemain.qml#include "qtquick2applicationviewer.h"#include #include #include 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));}
import 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: 360 height: 360 ColumnLayout { id: columnLayout1 x: 8 y: 15 width: 310 height: 324 Label { id: label2 x: 83 y: -37 width: 178 height: 12 text: "十六进制和十进制转换器 by jdh" } RowLayout { id: rowLayout1 x: 0 y: -216 width: 310 height: 50 spacing: 1 Label { id: label1 x: 0 y: -199 width: 57 height: 39 text: "输入:" } TextField { id: txt_in x: 71 y: -204 width: 254 height: 39 placeholderText: qsTr("Text Field") } } RowLayout { id: rowLayout2 x: 0 y: -153 width: 310 height: 50 Label { id: label3 x: 13 y: -151 width: 57 height: 39 text: "输出:" } TextField { id: txt_out x: 76 y: -151 width: 254 height: 39 placeholderText: qsTr("Text Field") } } RowLayout { id: rowLayout3 x: 0 y: -80 width: 310 height: 50 Button { id: btn_2dec x: 13 y: -75 width: 108 height: 44 text: "转十进制" onClicked: btn_2dec_click(txt_in.text) } Button { id: btn_2hex x: 222 y: -75 width: 108 height: 44 text: "转十六进制" onClicked: btn_2hex_click(txt_in.text) } } } function disp(str_num) { txt_out.text = str_num }}运行效果:
再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!