简体   繁体   中英

Get Control under cursor

I`m try to get control under cursor. At my example i can get only red rectangle, but i need get other also.

import QtQuick 2.4
import QtQuick.Controls 1.3
import QtQuick.Window 2.2
import QtQuick.Dialogs 1.2

ApplicationWindow {
    id: mainWindow
    title: qsTr("Hello World")
    width: 640
    height: 480
    Item {
        id: parentPanel
        anchors.fill: parent

        MouseArea {
            anchors.fill: parent
            hoverEnabled: true
            onMouseXChanged: moveMouse()
            onMouseYChanged: moveMouse()
            function moveMouse()
            {
                currentControl.text = parentPanel.childAt(mouseX, mouseY).color ? parentPanel.childAt(mouseX, mouseY).color : "not colored"
            }
        }

        Rectangle {
            id: redRect
               anchors {
                fill: parent
                leftMargin: 50
                bottomMargin: 50
            }
            color: "red"
            Rectangle {
                id: yellowRect
                anchors {
                    fill: parent
                    leftMargin: 50
                    bottomMargin: 50
                }
                color: "yellow"
                Rectangle {
                    id: greenRect
                    anchors {
                        fill: parent
                        leftMargin: 50
                        bottomMargin: 50
                    }
                    color: "green"
                }
            }
        }

        Text {
            id: currentControl
            anchors.left: parent.left
            anchors.bottom: parent.bottom
        }
    }
}

I have screenshot from running program. Green rect inside yellow, yellow inside red. I need get control ref when mouse cursor over control.

成功变成红色

I'm not familiar with QML, so I don't know the exact syntax for this, but it seems like you want to loop until you find the inner-most control and get the color of that. Here's some C++ish pseudo-code

auto control = parentPanel.childAt(mouseX, mouseY);
while (control)
{
    currentControl.text = control.color ? control.color : "not colored";
    control = control.childAt(mouseX, mouseY);
}

Of course, this code assumes that the X and Y passed are absolute, not relative. If the are relative, you would need to decrement them by the location of control in each consecutive loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM