Getting data from child using PyQt

2019-09-04 23:44发布

问题:

I am building a simple application that opens a QDialog, and from a QComboBox that belongs to the child, I can select an item and see some information. What I need to do is to get some of the information shown by the selected item from the comboBox (or another data of this child).

This is the code that i am using to open the child widget:

class Window(QMainWindow):
  def __init__(self):
    #A lot of stuff in here

  #I connect a QPushButton to this method to open the child
  def Serial_connection(self, event):
    configurePort.ConfigurePort(self).show()

And this is the code of the child:

class ConfigurePort(QDialog):
  def __init__(self, parent = None):
    QDialog.__init__(self, parent)
    uic.loadUi("configurePort.ui", self)

    self.initUi()

  def initUi(self):
    self.comboBox.activated[str].connect(self.Selected)
    self.label.hide()

  def Selected(self, text):
    if text == "option 1":
      self.label.setText("Option 1 selected")

Now, from the Selected method, I need to get the text: "Option 1 selected" and send it to the parent (the QMainWindow) to use this information to do another thing.

How can I do this? How can I retrieve data from a child? Hope you can help me.

回答1:

Generally, when you're using a temporary dialog to get information from the user, the dialog should be modal, so you can block all other actions until the user is finished with the dialog. It also allows you to call the dialog much like a function, and get results back from it.

Here is an example of a modal dialog that returns the text results.

class ConfigurePort(QDialog):
    def __init__(self, parent = None):
        QDialog.__init__(self, parent)
        uic.loadUi("configurePort.ui", self)

        self.initUi()

    def initUi(self):
        self.comboBox.activated[str].connect(self.Selected)
        self.label.hide()

    def Selected(self, text):
        if text == "option 1":
            self.label.setText("Option 1 selected")

    def getLabelText(self):
        return self.label.text()

    @classmethod
    def launch(cls, parent=None):
        dlg = cls(parent)
        dlg.exec_()
        text = dlg.getLabelText()
        return text


class Window(QMainWindow):
    ...
    def Serial_connection(self, event):
        text = configurePort.ConfigurePort.launch(self)
        print text