将光标坐标发送到C ++并将其存储在结构中并追加到main.qml

问题描述

我可以在(x,y)的某些位置拖动图像小部件,我可以使用功能console.log()来获得这些坐标并在控制台上看到它们

我需要的是将这些(x,y)坐标发送到C ++并将其存储在结构中。

我的任务是在图像小部件中附加(x,y)坐标值 main.qml

ImageWidget {
    id: phone_icon
    x:353;y:96
    height:63;width:37
    onXChanged: {
        console.error(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>  X = ",x)
        Update.update_datax(X)
    }
    onYChanged: {
        console.error(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>  Y = ",y)
        Update.update_dataY(Y)
    }
}

解决方法

以下是准则示例。

实施:

  • 在窗口上移动鼠标时,获取鼠标光标的x,y坐标值
  • 将X和Y值发送到C ++端
  • 将值存储在struct内部的数组中
  • 单击测试按钮时,它将显示存储的数组元素。

main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <store.h>
#include <QQmlApplicationEngine>
#include <QQmlContext>
int main(int argc,char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc,argv);
    qmlRegisterType<Store>("Store",1,"Store");
    Store store;

    QQmlApplicationEngine engine;
    engine.rootContext()->setContextProperty("Store",&store);

    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine,&QQmlApplicationEngine::objectCreated,&app,[url](QObject *obj,const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    },Qt::QueuedConnection);
    engine.load(url);

    return app.exec();
}

store.cpp

#include "store.h"
#include <iostream>
using namespace std;


struct coordinates
{
    vector<int> x_points;
    vector<int> y_points;

}call_struct;

Store::Store(QObject *parent)
{

}

void Store::store_dataX(int x)
{
    call_struct.x_points.push_back(x);
}

void Store::store_dataY(int y)
{
    call_struct.y_points.push_back(y);

}

void Store::result()
{
    for(int kk:call_struct.x_points)
        cout<<kk<<endl;
}

store.h

#ifndef STORE_H
#define STORE_H

#include <QObject>


class Store: public QObject
{
    Q_OBJECT
public:
    explicit Store(QObject *parent = nullptr);

public slots:

    void store_dataX(int x);
    void store_dataY(int y);
    void result();


};

#endif // STORE_H

main.qml

import QtQuick 2.14
import QtQuick.Window 2.14
import QtQuick.Controls 2.0

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    MouseArea{
        anchors.fill: parent

        hoverEnabled: true

        onMouseXChanged:
        {
            Store.store_dataX(mouseX)
        }
        
        onMouseYChanged:
        {
            Store.store_dataY(mouseY)
        }
    }

    Button{
        text: "Test"
        onClicked: Store.result()
    }
}