Heesung Yang

[문제 해결] Qt Quick 2 / QML - Unable to assign QQuickWindowQmlImpl to QQuickItem

현상

아래 코드 실행 시 다음과 같은 에러가 발생하며 MouseArea 적용이 되지 않음

main.qml:13:9: Unable to assign QQuickWindowQmlImpl to QQuickItem
  • main.py

    import os
    from pathlib import Path
    import sys
    
    from PySide2.QtGui import QGuiApplication
    from PySide2.QtQml import QQmlApplicationEngine
    
    
    if __name__ == "__main__":
        app = QGuiApplication(sys.argv)
        engine = QQmlApplicationEngine()
        engine.load(os.fspath(Path(__file__).resolve().parent / "main.qml"))
        if not engine.rootObjects():
            sys.exit(-1)
        sys.exit(app.exec_())
    
  • main.qml

    import QtQuick 2.15
    import QtQuick.Window 2.15
    
    Window {
        id: root
    
        width: 640
        height: 480
        title: "Hello, world"
        visible: true
    
        MouseArea {
            anchors.fill: root
    
            onClicked: {
                root.title = "Clicked"
            }
        }
    }
    

원인

anchor 속성은 성능상의 이유로 같은 depth의 컴포넌트나 바로 상위 컴포넌트만 설정할 수 있다.

https://doc.qt.io/qt-5/qtquick-positioning-anchors.html#restrictions

For performance reasons, you can only anchor an item to its siblings and direct parent. For example, the following anchor is invalid and would produce a warning:

해결 방안

  • main.qml

    import QtQuick 2.15
    import QtQuick.Window 2.15
    
    Window {
        id: root
    
        width: 640
        height: 480
        title: "Hello, world"
        visible: true
    
        MouseArea {
            anchors.fill: parent      // root -> parent로 수정
    
            onClicked: {
                root.title = "Clicked"
            }
        }
    }
    

참고