簡體   English   中英

如何在自定義組件中聲明 EventHandler(插槽?)類型的屬性並為其分配 function

[英]How to declare a property of type EventHandler (slot?) in Custom Component and assign function for that in its usage

對於我的自定義 window,如答案所示,我創建了一個名為PathButton的組件

import QtQuick 2.0
import QtQuick.Shapes 1.12

Item {
    property alias pathData: svg.path
    width: 24
    height: 24
    Shape {
        ShapePath {
            fillColor: "black"
            PathSvg {
                id: svg
                path: pathData
            }
        }
    }
}

並用它來minimizemaximizeclose window,如下所示:

RowLayout{
    Layout.preferredWidth: 100
    anchors.right: title.right
    PathButton{
        pathData: ViewModel.minimizeIcon
        MouseArea{
            anchors.fill: parent
            onClicked: mainWindow.showMinimized()
        }
    }
    PathButton{
        pathData: ViewModel.maximizeIcon
        MouseArea{
            anchors.fill: parent
            //this doesn't restore the window to its Normal state, showMaximized() is called always
            onClicked: mainWindow.Maximized? mainWindow.showNormal() : mainWindow.showMaximized()
        }
    }
    PathButton{
        pathData: ViewModel.closeIcon
        MouseArea{
            anchors.fill: parent
            onClicked: mainWindow.close()
        }
    }
}

在所有這些我有一個MouseArea 我想要的是在我的自定義組件中有那個MouseArea並聲明一個eventhandler/signal/slot類型的屬性並將該處理程序分配給onClicked ,如下所示:

import QtQuick 2.0
import QtQuick.Shapes 1.12

Item {
    property alias pathData: svg.path
    property alias handler: mouse.onClicked
    width: 24
    height: 24
    Shape {
        ShapePath {
            fillColor: "black"
            PathSvg {
                id: svg
                path: pathData
            }
        }
    }
    MouseArea{
        id: mouse
        anchors.fill: parent
        onClicked: handler
    }
}

在它的使用中,我想像這樣分配相關的 function :

PathButton{
    pathData: ViewModel.minimizeIcon
    handler: mainWindow.showMinimized()
}

編輯

這是我在PathButton.qml中的內容:

import QtQuick 2.0
import QtQuick.Shapes 1.12

Item {
    id: root
    property alias pathData: svg.path
    signal onClicked()

    width: 24
    height: 24
    Shape {
        ShapePath {
            fillColor: "black"
            PathSvg {
                id: svg
                path: pathData
            }
        }
    }
    MouseArea{
        anchors.fill: parent
        onClicked: root.onClicked()
    }
}

main.qml中,我收到該錯誤,當我遇到該錯誤運行時,在 Application Output 中,我收到另一個錯誤:

在此處輸入圖像描述

我認為您正在尋找的只是一個信號:

// PathButton.qml
Item {
    id: root
    signal clicked()

    ...

    MouseArea {
        onClicked: root.clicked()
    }
}

然后你會像這樣使用它:

PathButton {
    onClicked: mainWindow.showMinimized()
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM