获取QuickControl的屏幕坐标

时间:2015-09-08 06:28:15

标签: qt qml coordinates qtquick2 qtquickcontrols

我必须设置QWindow的x,y坐标。此QWindow必须获取QuickControl + MainWindowmyValue的屏幕坐标。

如何在QML中获取QuickControl的全局屏幕坐标?

3 个答案:

答案 0 :(得分:3)

如@BaCaRoZzo所述,使用mapToItem() / mapFromItem()函数:

import QtQuick 2.0
import QtQuick.Window 2.0
import QtQuick.Controls 1.0

Window {
    id: window
    width: 400
    height: 400
    visible: true

    Button {
        id: button
        text: "Button"
        x: 100
        y: 100

        readonly property point windowPos: button.mapToItem(null, 0, 0)
        readonly property point globalPos: Qt.point(windowPos.x + window.x, windowPos.y + window.y)
    }

    Column {
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.bottom: parent.bottom

        Text {
            text: "Button position relative to window: x=" + button.windowPos.x + " y=" + button.windowPos.y
        }

        Text {
            text: "Button position relative to screen: x=" + button.globalPos.x + " y=" + button.globalPos.y
        }
    }
}

正如mapToItem() windowPos中提到的那样:

  

将此项目坐标系中的点(x,y)或矩形(x,y,宽度,高度)映射到项目的坐标系,并返回一个点或矩形匹配映射的坐标。

     

如果item为空值,则将point或rect映射到根QML视图的坐标系。

这给了我们x。要获取控件相对于屏幕本身的位置,我们只需添加窗口的yclass Control : public QQuickItem { Q_OBJECT public: Control() {} ~Control() {} public slots: void printGlobalPos() { qDebug() << mapToItem(Q_NULLPTR, QPointF(0, 0)) + window()->position(); } }; 位置。

与OP聊天后,很清楚他想用C ++做这件事。同样的原则适用,在C ++中我们可以更方便地访问窗口:

qmlRegisterType<Control>("Types", 1, 0, "Control");

注册类型:

import QtQuick 2.0
import QtQuick.Window 2.0

import Types 1.0

Window {
    id: window
    width: 400
    height: 400
    visible: true

    Control {
        id: button
        x: 100
        y: 100
        width: 100
        height: 40

        MouseArea {
            anchors.fill: parent
            onClicked: button.printGlobalPos()
        }

        Rectangle {
            anchors.fill: parent
            color: "transparent"
            border.color: "darkorange"
        }
    }
}

在QML中使用它:

[HttpPost, ActionName("GetEmpsByPinAndCityName")]
[EnableQuery]
public IHttpActionResult GetEmpsByPinAndCityName(int pincode, string cityName)
{
    var result = this.context.EmpSets.Where(x => x.PinCode == pincode & x.CityName == cityName).ToList();
    return result;
}

答案 1 :(得分:1)

对于xy坐标相对于所有项目的父项而不是最高项目(又名Window),您至少可以通过父项来获取它们链到主Window,这些变量表示相对于Screen的位置。

这是在通过母链的过程中增加和减少的问题,确实非常烦人,但我不知道是否存在另一种解决方案。

答案 2 :(得分:0)

object mapFromGlobal(real x,real y)

将全局坐标系中的点(x,y)映射到项的坐标系,并返回与映射坐标匹配的点。 QML方法在Qt 5.7中引入。

相关问题