Qt and QML interaction, and multithreading

Source: Internet
Author: User

To register an object to QML, implement the code:
Gamesub.h

#pragma once#include <QObject>#include <QVariant>#include <QQmlApplicationEngine>#include <QquickItem>class gamesub:p ublicQobject{Q_objectPublicgamesub(qobject* Parent=NULL); ~gamesub();Qqmlapplicationengine* M_MAINROOT;Qquickitem* M_PAGE;q_invokablevoid Setpage(qquickitem* page); void Setroot(qqmlapplicationengine* mainroot);q_invokablevoid Init();q_invokablevoid msg(qvariantvar)  ;q_invokable qvariantGetobj();};

Gamesub.cpp

#include "Gamesub.h"Gamesub::gamesub (qobject* Parent): Qobject (parent) {}gamesub::~gamesub () {}q_invokablevoidGamesub::setpage (qquickitem* page) {m_page = page; Outputdebugstringa (M_page->objectname (). tostdstring (). C_STR ());intcout =0;D Word thtest (LPVOID LP) {qquickitem* m_page = (qquickitem*) LP; Qvariant item;//blockingqueuedconnection is used in multiple threads, otherwise an error occurs    BOOLRet2 = Qmetaobject::invokemethod (M_page,"GetItem", Qt::connectiontype::blockingqueuedconnection, Q_return_arg (qvariant, item), Q_arg (Qvariant, cout));if(Ret2 = =false) {AfxMessageBox ("ERROR");    } qobject* obj; obj = Item.value<QObject*> ();///Item.typename () can be used to get the return value type, then convert using item.value< type > ()    int  var=0; while(true)    {var=var+1;if(Obj!=null && isbadwriteptr (obj,4)==false) {Qmetaobject::invokemethod (obj,"Test", Qt::connectiontype::queuedconnection, Q_arg (Qvariant, Qstring::number (var)));//can also be modified here to Qt::connectiontype::blockingqueuedconnection} Sleep ( +); }return  0;} Q_invokablevoidGamesub::init () { for(intI=0;i<5; i++) {qvariant s;        s = i; Qmetaobject::invokemethod (M_page,"Addmodel", Q_arg (Qvariant, s.tostring ()));    } qvariant ret; Qmetaobject::invokemethod (M_page,"Getlen", Q_return_arg (qvariant, ret));//afxmessagebox (Ret.typename ());AfxMessageBox (Ret.tostring (). tostdstring (). C_STR ()); Qvariant item;BOOLRet2 = Qmetaobject::invokemethod (M_page,"GetItem", Q_return_arg (Qvariant, item), Q_arg (Qvariant,0));if(Ret2 = =false) {AfxMessageBox ("ERROR");    } qobject* obj; obj = Item.value<QObject*> (); AfxMessageBox (Obj->objectname (). tostdstring (). C_STR ()); for(inti =0; I < Ret.toint ();        i++) {AfxBeginThread (Afx_threadproc (thtest), m_page); Sleep ( -);    cout++; }}voidGamesub::setroot (Qqmlapplicationengine * mainroot) {m_mainroot = Mainroot;} Q_invokablevoidGamesub::msg (qvariantvar) {AfxMessageBox (var. toString (). tostdstring (). C_STR ()); Q_invokable qvariant gamesub::getobj () {if(M_mainroot!=null) {Qobject *tmp = M_mainroot->findchild<qobject *> ("Mmodel");if(Tmp!=null) {Outputdebugstringa ("OK object"); }Else{Outputdebugstringa ("Null Object"); }    }return 0;}

Main.cpp:

//Register First for classQmlregistertype<Gamesub>("Game",1,0,"Game"); Qapplication*App=(qapplication*) qapplication:: Instance(); Outputdebugstringa ("Local File");    Qqmlapplicationengine engine (APP); Gamesub*Tmp= NewGamesub (); Tmp -M_mainroot= &Engine Engine.Rootcontext () -Setcontextproperty ("Game", (Qobject*) TMP); Engine.Load (qurl:: Fromlocalfile(Qstringliteral ("MAIN.QML")));

Click Run, C + + code dynamically add model, and in multi-threading, Refresh UI
QML file:
Main.qml

Import QtQuick2.6Import QtQuick. Window 2.2Import Material0.1As Materialimport Material. ListItems 0.1As Listitemsimport Material. Extras 0.1As Exmaterial. Applicationwindow{Property Item tmp:null visible:true title:"main Window"property var mytabs: ["Main"] theme{primarycolor:material. Palette. Colors["Blue"]["a"] Primarydarkcolor:material. Palette. Colors["Blue"][" the"] Accentcolor:material. Palette. Colors["Teal"]["a"] Tabhighlightcolor:"White"} initialpage:material. Page{id:mainpage title:"main Window"Tabs:mytabs onselectedtabchanged: {if (selectedtab==1) {Mainrun. Visible=false Loader. SOURCE=qt. Resolvedurl("RUN2.QML") Loader. Visible=true}else{Mainrun. Visible=true Loader. Visible=false}} loader{anchors. Fill: Parent Visible:false id:loader//SOURCE:QT. Resolvedurl("RUN2.QML")} Material. Button{Id:mainrun visible:true text:"Run"Elevation:1OnClicked: {mytabs[1]="In Progress"MainPage. Tabs=mytabs mainpage. Selectedtab=1text="Runing"}}} droparea{anchors. Fill: Parent ondropped: {for (Var i=0; i<drop.urls.length;i++){Title=title+drop. Text+","}            }        }}

RUN2.QML:

Import QtQuick2.6Import QtQuick. Window 2.2Import Material0.1As Materialimport Material. ListItems 0.1As Listitemsimport Material. Extras 0.1As Exmaterial. View{ID:PageObjectName: "Mmodel"Component. Ondestruction: {Console. Log("Ondestruction")} flow{spacing:5Anchors. Fill: Parent repeater{Id:rey Model:mmodel delegate:componet } Component. oncompleted: {Game. Setpage(page);Game. Init();}} listmodel{Id:mmodel listelement{txt:"Test"} listelement{txt:"Test2"} listelement{txt:"Test3"}} component{id:componet Material. View{Id:m_view ObjectName:"Index"Elevation:3Width -Height -Anchors. Margins:5column{width:parent. WidthMaterial. Button{ID:BTN Elevation:1Width:parent. WidthText:txt;} repeater{Model:mmodel2 Delegate:listitems. Standard{Valuetext:index Itemlabel. Font. Pixelsize: -Elevation:1Id:labels Text:shows}}} listmodel{Id:mmodel2 listelement{shows:"Test"}} function test (TXT) {if (Mmodel2. Count>5) {Mmodel2. Clear() Mmodel2. Sync()} Mmodel2. Append({shows:txt})} }} function GetItem (index) {var i= rey. Itemat(index) Console. Log("Index:"+index+":"+i) return I;} function Addmodel (argtxt) {Mmodel. Append({txt:argtxt})} function Getlen () {return Mmodel. Count;}}

Qt and QML interaction, and multithreading

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.