下面的代码创建了一个对话框,在按 "Enter "键和按 "OK "键之间发生了不一致的行为。按 "回车 "键和按 "确定 "键之间的行为不一致。当改变一个字段时按下回车键,只有该字段被更新。当按下 "确定 "键时,两个字段都会被更新(首选)。如何覆盖回车键在这里做合理的事情?
我真正想要的是,如果回车键能在不关闭对话框的情况下将更新的字段送回应用程序,因为我想在对话框中控制一些东西。
视图.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()
}
}