我是python中的信号和插槽的新手,目前正在使用Pyqt5设计GUI。用户需要从qcombobox的组合中进行选择,其中每个元素都是一个qmenu。我正在尝试存储用户使用信号选择的路径。
选择GUI的图像
尝试:
在类中将pathChanged使用为:
pathChanged = QtCore.pyqtSignal(list)
,然后在 init 中使用以下命令打印所选路径:
combo.pathChanged.connect(print)
但这不会将我的路径的值保存到变量中,而只是在控制台上显示它。如果我将上述等同于变量,那么我只会收到内存位置。
如何将选择存储在列表中,并且在每次用户选择后都将列表追加?
尝试通过原始代码https://stackoverflow.com/a/52723148/6942881
来实现该想法我的代码是:
from PyQt5 import QtCore, QtWidgets
data = {'Concept': {
"Aircraft":{
"Blended Wing":[],
"Lifting Body":["Flat Bottom","Round Bottom","Wing"],
"Wing Body":["Fixed","Rotary","Swept"]},
"Launch Vehicle":{
"SSTO":["Expendable","Reusable","Partially Reusable"],
"TSTO":["Expendable","Reusable","Partially Reusable"],
"MSTO":["Expendable","Reusable","Partially Reusable"]}
}
}
class ComboBoxExpandable(QtWidgets.QPushButton):
currentTextChanged = QtCore.pyqtSignal(str)
pathChanged = QtCore.pyqtSignal(list)
def setData(self, value):
menu = QtWidgets.QMenu(self)
self.setMenu(menu)
self.append_element(value, menu)
menu.triggered.connect(self.on_triggered)
def printer(self,path):
# print(path)
return path
@QtCore.pyqtSlot(QtWidgets.QAction)
def on_triggered(self, action):
self.setText(action.text())
path = [action.text()]
w = action.parentWidget()
while w.parentWidget() and isinstance(w.parentWidget(), QtWidgets.QMenu):
path.insert(0, w.title())
w = w.parentWidget()
self.pathChanged.emit(path)
self.currentTextChanged.emit(self.text())
self.printer(path)
@staticmethod
def append_element(value, menu):
if isinstance(value, list):
for e in value:
ComboBoxExpandable.append_element(e, menu)
elif isinstance(value, dict):
for k, v in value.items():
if v==[]:
menu.addAction(k)
else:
ComboBoxExpandable.append_element(v, menu.addMenu(k))
else:
menu.addAction(value)
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
combo = ComboBoxExpandable()
combo.setData(data)
result_label = QtWidgets.QLabel()
combo.currentTextChanged.connect(result_label.setText)
combo.pathChanged.connect(print)
lay = QtWidgets.QFormLayout(self)
lay.addRow("Select Concept: ", combo)
lay.addRow("Concept Selected: ", result_label)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
答案 0 :(得分:1)
解决方案是创建一个连接到该信号的插槽,其中将通过信号传输的列表添加到该类的成员中:
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
self._paths = [] # <---container
combo = ComboBoxExpandable()
combo.setData(data)
result_label = QtWidgets.QLabel()
combo.currentTextChanged.connect(result_label.setText)
combo.pathChanged.connect(self.on_pathChanged)
lay = QtWidgets.QFormLayout(self)
lay.addRow("Select Concept: ", combo)
lay.addRow("Concept Selected: ", result_label)
@QtCore.pyqtSlot(list)
def on_pathChanged(self, path):
self._paths.append(path) # append path
print(self._paths)