如何在QML对话框中更改输入键的行为?



以下代码创建一个对话框。按"Enter"键和点击"确定"按钮之间发生了不一致的行为。在更改字段时按回车键时,仅更新该字段。按下"确定"按钮时,两者都会更新(这是首选(。如何覆盖 Enter 键以在此处执行合理的操作?

我真正想要的是,如果 enter 键在不关闭对话框的情况下将更新的字段发送回应用程序,因为我想从对话框中控制某些内容。

view.qml

import QtQuick 2.0
import QtQuick.Layouts 1.12
import QtQuick.Controls 2.12
import QtQuick.Window 2.12
import QtQuick.Dialogs 1.3

Item {
Dialog {
id: thedialog
ColumnLayout {
TextField {
id: numberField
onAccepted: {
backend.number = text
}
}
TextField {
id: textField
onAccepted: {
backend.text = text
}
}
}
onButtonClicked: {
backend.number = numberField.text
backend.text = textField.text
}
}
Button {
text: "Show Dialog"
onClicked: thedialog.open()
}
}

main.py

import sys
from PySide2.QtCore import QObject, Signal, Property
from PySide2.QtWidgets import QApplication, QMainWindow
from PySide2.QtQuickWidgets import QQuickWidget
class Backend(QObject):
def __init__(self):
QObject.__init__(self)
self._number = 0
self._text = ""
def getNumber(self):
return self._number
def setNumber(self, number):
print(f"Setting number to: {number}")
self._number = number
self.notifyNumber.emit()
notifyNumber = Signal()
number = Property(float, getNumber, setNumber, notify=notifyNumber)
def getText(self):
return self._text
def setText(self, text):
print(f"Setting text to: {text}")
self._text = text
self.notifyText.emit()
notifyText = Signal()
text = Property(str, getText, setText, notify=notifyText)

if __name__ == '__main__':
app = QApplication(sys.argv)
window = QMainWindow()
quick = QQuickWidget()
backend = Backend()
quick.rootContext().setContextProperty("backend", backend)
quick.setSource("view.qml")
window.setCentralWidget(quick)
window.show()
sys.exit(app.exec_())

使用附加的密钥 API:

import QtQuick 2.14
import QtQuick.Layouts 1.14
import QtQuick.Controls 2.14
ApplicationWindow {
width: 800
height: 600
visible: true
QtObject {
id: backend
property real number
property string text
}
Dialog {
id: thedialog
function doSomeStuffBeforeClosingTheDialog() {
backend.number = parseFloat(numberField.text)
backend.text = textField.text
// Remove this if you do not want the dialog to close
accept()
}
ColumnLayout {
TextField {
id: numberField
onAccepted: backend.number = text
Keys.onReturnPressed: thedialog.doSomeStuffBeforeClosingTheDialog()
}
TextField {
id: textField
onAccepted: backend.text = text
Keys.onReturnPressed: thedialog.doSomeStuffBeforeClosingTheDialog()
}
}
}
Button {
text: "Show Dialog"
onClicked: thedialog.open()
}
}

最新更新