【发布时间】:2021-06-05 05:55:13
【问题描述】:
我正在使用 PySide2 并创建一个组合框,我试图在按下提交按钮时发送选定的值,视觉示例:
当按下提交 test1 应该在终端上打印时,我尝试使用 Slots 但按下提交按钮时没有任何反应。
我的代码: main.py:
import sys
import os
from os.path import join, dirname, abspath
from PySide2.QtCore import QStringListModel, QObject, Slot
from PySide2.QtGui import QGuiApplication
from PySide2.QtQml import QQmlApplicationEngine
class Combo(QObject):
def __init__(self, parent=None):
super().__init__()
self.model = QStringListModel(['test1', 'test2'])
@Slot(str, result=None)
def submit(self, text_val):
print('test')
print(text_val, self.model.text)
if __name__ == '__main__':
app = QGuiApplication(sys.argv)
engine = QQmlApplicationEngine()
comobo_box = Combo()
context = engine.rootContext()
context.setContextProperty("comobo_box", comobo_box)
context.setContextProperty("stringModel", comobo_box.model)
qmlFile = join(dirname(__file__), r'main.qml')
engine.load(abspath(qmlFile))
if not engine.rootObjects():
sys.exit(-1)
app.exec_()
main.qml:
import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Layouts 1.15
import QtQuick.Controls 2.15
Window {
id: window
visible: true
height: 200
width: 400
property string textVal: ""
Rectangle {
color: '#041645'
id: mainArea
anchors.fill: parent
ColumnLayout {
anchors.fill: parent
ComboBox {
id: cBox
Layout.alignment: Qt.AlignHCenter | Qt.AlignVCenter
model: stringModel
textRole: "display"
Button {
id: submit
x: -50
y: 100
text: qsTr("Submit")
onClicked: {
comobo_box.submit(model.text)
}
}
Button {
id: cancel
x: 75
y: 100
text: qsTr("Cancel")
onClicked: {
window.close()
}
}
}
RowLayout{
Layout.alignment: Qt.AlignHCenter
}
}
}
}
【问题讨论】:
标签: python combobox qml pyside2