显示消息对话框

时间:2019-04-23 15:29:43

标签: qt qml qtquick2 qt5.12

当用户在QML窗口中单击按钮时,是否可以显示QML对话框?

示例

当用户单击帮助->关于上的菜单栏中时,应显示“关于”对话框:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Enable AR related functionality on ARCore supported devices only.
    maybeEnableArButton();
}

void maybeEnableArButton() {
    ArCoreApk.Availability availability = ArCoreApk.getInstance().checkAvailability(this);

    if (availability.isTransient()) {
        // Re-query at 5Hz while compatibility is checked in the background.
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                maybeEnableArButton();
            }
        }, 200);
    }
    if (availability.isSupported()) {
        mArButton.setVisibility(View.VISIBLE);
        mArButton.setEnabled(true);
        // indicator on the button.
    } else {                            // Unsupported or unknown.
        mArButton.setVisibility(View.INVISIBLE);
        mArButton.setEnabled(false);
    }
}

components / AboutDialog.qml

import QtQuick 2.12
import QtQuick.Layouts 1.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.12

import "components"

ApplicationWindow {
    id: window
    visible: true
    width: 1040
    height: 480


    aboutDlg: aboutDialog {}  // does not work...

    menuBar: MenuBar {
        Menu {
            title: qsTr("Help")
            MenuItem {
                text: qsTr("About")
                onTriggered: aboutDlg.open();
        }
    }
    ...

当我删除import QtQuick 2.2 import QtQuick.Dialogs 1.1 MessageDialog { id: aboutDialog title: "May I have your attention please" text: "It's so cool that you are using Qt Quick." onAccepted: { console.log("And of course you could only agree.") Qt.quit() } } 行时,单击关于菜单项时报告以下错误:

  

qrc:/main.qml:61:ReferenceError:aboutDlg未定义

我该如何实现?

1 个答案:

答案 0 :(得分:1)

您称为“ aboutDialog”,它是AboutDialog中的ID。 可以像添加一个对象(例如添加一个具有自己的文件的Rectangle ...)一样,然后通过添加一个对象来“实例化”它:

...

ApplicationWindow {

...

    AboutDialog {
        id: aboutDlg
    }

...
}

您可以找到示例HERE

您还可以进行一些优化,然后将AboutDialog放在Loader中。