如何使用多个类从QDialog获取值

时间:2018-11-06 19:00:09

标签: python pyside qdialog

我目前正在Nuke 11中的一个面板中打开QDialog,我想知道当我关闭QDialog时如何从它的值获取主类吗? QDialog在另一个类中。这是一个简化的示例,显示了我的问题:

import nuke
from nukescripts import panels
try:
  ## < Nuke11
    import PySide.QtGui as QtGui
    import PySide.QtCore as QtCore

except:
  ## >= Nuke11
    import PySide2.QtCore as QtCore
    import PySide2.QtGui as QtGui
    import PySide2.QtWidgets as QtGui
    from PySide2.QtWidgets import QWidget as QWidget

class Example(QtGui.QWidget):
    def __init__(self):
        super(Example,self).__init__()
        layout = QtGui.QVBoxLayout()

        button = QtGui.QPushButton('Get Value')
        button.clicked.connect(self.someFunction)

        layout.addWidget(button)
        self.setLayout(layout)

    def someFunction(self):
        value = self.GetValueLineEdit()
        if value :
            # do something

    def GetValueLineEdit(self):
        class getValuePanel(QtGui.QDialog):
            def __init__(self):
                super(getValuePanel, self).__init__()
                layout = QtGui.QHBoxLayout()

                self.lineEdit = QtGui.QLineEdit('')

                getValueButton = QtGui.QPushButton('Get Value')
                getValueButton.clicked.connect(self.getValue)

                layout.addWidget(self.lineEdit)
                layout.addWidget(getValueButton)
                self.setLayout(layout)

            def getValue(self):
                value = str(self.lineEdit.text())
                getValuePanel.accept() #To Close the QDialog
                return value

        getValuePanel = getValuePanel()
        getValuePanel.show()

pane = nuke.getPaneFor("Example.panel")
panels.registerWidgetAsPanel('Example', 'Example',"", True).addToPane(pane)

非常感谢

1 个答案:

答案 0 :(得分:1)

首先,您不要在其他类中创建类,这被认为是不好的做法。另一方面,未使用返回槽的操作,因为没有人收到它,因此返回getValue的操作将丢失,您必须做的是单击调用接受关闭QDialog,并在确认对话框已被接受之后,您只需调用getValue:

class ValuePanel(QtGui.QDialog):
    def __init__(self):
        super(ValuePanel, self).__init__()
        self.lineEdit = QtGui.QLineEdit()
        getValueButton = QtGui.QPushButton('Get Value')
        getValueButton.clicked.connect(self.accept)

        layout = QtGui.QHBoxLayout(self)
        layout.addWidget(self.lineEdit)
        layout.addWidget(getValueButton)

    def getValue(self):
        value = str(self.lineEdit.text())
        return value

class Example(QtGui.QWidget):
    def __init__(self):
        super(Example,self).__init__()
        button = QtGui.QPushButton('Get Value')
        button.clicked.connect(self.someFunction)

        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(button)

    @QtCore.Slot()
    def someFunction(self):
        value_panel = ValuePanel()
        if value_panel.exec_() == QtGui.QDialog.Accepted:
            print(value_panel.getValue())