移动窗口无法正常工作

时间:2019-03-23 18:25:01

标签: qt qml

问题是窗口的坐标设置不正确。因此,窗口移动不正确并出现错误:

QWindowsWindow :: setGeometry:无法在QQuickApplicationWindow_QML_0 /''上设置几何400x400 + 62998 + 32284 ...

我不知道该如何解决。这是代码:

main.qml

import QtQuick 2.12
import QtQuick.Controls 2.3
import QtQuick.Layouts 1.3

ApplicationWindow {
    id: window
    visible: true
    width: 400
    height: 400
    title: qsTr('Frameless')
    flags: Qt.Window | Qt.FramelessWindowHint

    Rectangle {
        width: parent.width
        height: 40
        color: "gold"

        anchors.top: parent.top

        Text {
            anchors.verticalCenter: parent.verticalCenter
            leftPadding: 8
            text: window.title
            color: "white"
        }

        MouseArea {
          anchors.fill: parent

          property real lastMouseX: 0
          property real lastMouseY: 0

          onPressed: {
             lastMouseX = mouse.x
             lastMouseY = mouse.y
          }
          onMouseXChanged: window.x += (mouse.x - lastMouseX)
          onMouseYChanged: window.y += (mouse.y- lastMouseY)
        }
    }
}

main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>


int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;

    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}

1 个答案:

答案 0 :(得分:1)

即使您设法使用QML解决此问题,您也会看到该窗口会随着很多抖动而移动。这主要是因为绑定是如何工作的(异步)。更好的方法是向C ++请求QCursor::pos()

这是执行此操作的简要方法:

在您的main.qml中创建一个MouseArea

MouseArea {
    property var clickPos
    anchors.fill: parent
    onPressed: {
        clickPos = { x: mouse.x, y: mouse.y }
    }
    onPositionChanged: {
        window.x = cpp_helper_class.cursorPos().x - clickPos.x
        window.y = cpp_helper_class.cursorPos().y - clickPos.y
    }
}

在您的c ++ cpp_helper_class中,您应该具有以下方法:

Q_INVOKABLE QPointF cursorPos() { return QCursor::pos(); }

Q_INVOKALBE确保可以从QML访问您的C ++代码。

另外,您的main.cpp应该包含以下内容:

context->setContextProperty("cpp_helper_class", &helper_class_instance);
相关问题