【问题标题】:Moving the window does not work correctly移动窗口无法正常工作
【发布时间】:2023-03-09 02:10:01
【问题描述】:

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

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();
}

【问题讨论】:

  • 您应该更仔细地阅读文档。 MouseArea.MouseArea 的参数是mouse。没有mouseXmouseY,因此您存储了一些随机值。另请注意,mouse.x 是真实的,因此在将其存储在 int 时会丢失精度。另一个建议是使用调试器,它可以立即解决此类问题。
  • 我稍微修正了我的代码,但效果仍然存在。也许你知道一个可行的解决方案?我想不通。
  • 没有id为mainWindow的项目,ApplicationWindow.visible默认为false,你必须明确设置为true。看起来您提供的代码与您测试的代码不同,并且还有一些其他因素会影响窗口位置。使用适合我的固定代码。
  • 我的项目中有两个文件:main.cpp 和 main.qml。我添加了它们。仍然对我不起作用。
  • window.x += (mouse.x - lastMouseX) 这始终是增量的,并且会无限增长。

标签: qt qml


【解决方案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 确保您的 C++ 代码可从 QML 访问。

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

context->setContextProperty("cpp_helper_class", &helper_class_instance);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-02
    • 1970-01-01
    • 2013-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多