我有一个简单的对话框,该对话框具有两个文本字段。我想在显示AddPasswordDialog
对话框时将文本字段labelField
焦点。我该如何实现?
我问了这个问题,我被要求提供一个MCVE,在这里我提供。如果需要的话,请询问更多信息。
main.qml
import QtQuick 2.7
import QtQuick.Controls 2.0
ApplicationWindow {
id: window
visible: true
width: 640
height: 480
title: qsTr("Stack")
header: ToolBar {
contentHeight: toolButton.implicitHeight
ToolButton {
id: toolButton
text: stackView.depth > 1 ? "u25C0" : "u2630"
onClicked: {
if (stackView.depth > 1) {
stackView.pop()
} else {
drawer.open()
}
}
}
}
StackView {
id: stackView
initialItem: "app/qml/HomeForm.qml"
anchors.fill: parent
}
}
HomeForm.qml
import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Controls 1.4
import QtQuick.Layouts 1.3
import QtQuick.Dialogs 1.2
Page {
id: mainPage
title: qsTr("Home")
GridLayout {
id: homeGrid
anchors.fill: parent
anchors.margins: 10
rows: 2
columns: 2
Button {
id: addButton
text: "Add"
Layout.row: 0
Layout.column: 0
anchors.right: parent.horizontalCenter
anchors.topMargin: 5
onClicked: {
var component = Qt.createComponent("AddPasswordDialog.qml")
var loadAddPwDialog = component.createObject(mainPage)
// loadAddPwDialog.labelField.forceActiveFocus()
loadAddPwDialog.open()
if (component.status === Component.Error) {
console.log("Error")
}
}
}
Button {
id: removeButton
text: "Remove"
Layout.row: 0
Layout.column: 1
anchors.left: addButton.right
anchors.topMargin: 5
anchors.leftMargin: 5
}
}
}
AddPasswordDialog.qml
import QtQuick 2.0
import QtQuick.Dialogs 1.2
import QtQuick.Controls 1.4
import QtQuick.Layouts 1.3
Dialog {
id: addPwDialog
modality: Qt.WindowModal
title: "Add a new password"
standardButtons: StandardButton.Save | StandardButton.Cancel
onAccepted: {
console.log("Accepted")
// pwDataModel.addPassword(labelField.text, pwField.text)
}
GridLayout {
TextField {
id: labelField
placeholderText: "Label"
focus: true
Layout.row: 0
Layout.column: 0
}
TextField {
id: pwField
placeholderText: "Password"
Layout.row: 1
Layout.column: 0
}
}
}
main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlEngine>
#include <QQmlComponent>
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("app/qml/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
可见时必须激活labelField
的焦点。
import QtQuick 2.0
import QtQuick.Dialogs 1.2
import QtQuick.Controls 1.4
import QtQuick.Layouts 1.3
Dialog {
id: addPwDialog
modality: Qt.WindowModal
title: "Add a new password"
standardButtons: StandardButton.Save | StandardButton.Cancel
onAccepted: {
console.log("Accepted")
//pwDataModel.addPassword(labelField.text, pwField.text)
}
onVisibleChanged: if(visible) labelField.focus = true
GridLayout {
TextField {
id: labelField
placeholderText: "Label"
Layout.row: 0
Layout.column: 0
}
TextField {
id: pwField
placeholderText: "Password"
Layout.row: 1
Layout.column: 0
}
}
}