QML之对话框

QML 提供了多种方式来实现对话框功能,以下是常用的几种方法:

1. 使用 QtQuick.Dialogs 模块

qml

import QtQuick.Dialogs

// 文件对话框
FileDialog {
    id: fileDialog
    title: "请选择文件"
    folder: shortcuts.home
    onAccepted: console.log("选中文件: " + fileDialog.fileUrl)
}

// 消息对话框
MessageDialog {
    id: messageDialog
    title: "提示"
    text: "操作已完成"
    buttons: MessageDialog.Ok
}

2. 自定义对话框组件

qml

// CustomDialog.qml
Rectangle {
    id: root
    width: 300
    height: 200
    color: "white"
    border.color: "gray"
    visible: false
    
    property string title: "对话框"
    
    Text {
        text: root.title
        font.bold: true
        anchors.top: parent.top
        anchors.horizontalCenter: parent.horizontalCenter
    }
    
    MouseArea {
        anchors.fill: parent
        // 阻止点击事件穿透到背景
    }
}

3. 使用 Popup 组件

qml

import QtQuick.Controls 2.15

Popup {
    id: popup
    width: 200
    height: 100
    modal: true
    focus: true
    
    Column {
        anchors.centerIn: parent
        Text { text: "这是一个弹出对话框" }
        Button {
            text: "关闭"
            onClicked: popup.close()
        }
    }
}

// 打开对话框
Button {
    text: "显示对话框"
    onClicked: popup.open()
}

4. 对话框最佳实践

  1. 模态与非模态

    • 使用 modal: true 使背景变暗并阻止背景交互

    • 设置 dim: true 使背景变暗

  2. 动画效果

    qml

    enter: Transition {
        NumberAnimation { property: "opacity"; from: 0.0; to: 1.0 }
    }
    exit: Transition {
        NumberAnimation { property: "opacity"; from: 1.0; to: 0.0 }
    }
  3. 定位方式

    • anchors.centerIn: Overlay.overlay 居中显示

    • 使用 x 和 y 自定义位置

  4. 响应式设计

    qml

    width: Math.min(400, parent.width * 0.8)
    height: Math.min(300, parent.height * 0.8)

5. 完整示例

qml

import QtQuick.Controls 2.15

ApplicationWindow {
    visible: true
    width: 400
    height: 300
    
    Button {
        text: "显示对话框"
        anchors.centerIn: parent
        onClicked: dialog.open()
    }
    
    Dialog {
        id: dialog
        title: "自定义对话框"
        standardButtons: Dialog.Ok | Dialog.Cancel
        
        Column {
            spacing: 20
            anchors.fill: parent
            
            Text { text: "这是一个自定义内容区域" }
            TextField { placeholderText: "输入内容" }
        }
        
        onAccepted: console.log("对话框确认")
        onRejected: console.log("对话框取消")
    }
}