PDA

View Full Version : Return values from QDialog to MainWindow



ecce
16th April 2015, 19:53
I've created a simple custom QDialog with three QLineEdits. When clicking the "OK" button I want to read the entered text and return them to the MainWindow object where the values will be stored in a list.

How do I return the values from the QDialog class so I can store them in the list in the MainWindow class, and how do I call it properly?

This is the code I have at the moment:


class MainWindow(QtGui.QMainWindow):

deviceList = []

def openAddDialog(self):
print "running openAddDialog..."
diag = AddDevice()



from PySide.QtGui import *

class AddDevice(QDialog):

def __init__(self):
QDialog.__init__(self)
self.setWindowTitle("Add Device")
self.resize(400, 300)

iLabel = QLabel("IPv4 address:")
self.iText = QLineEdit()

uLabel = QLabel("Username:")
self.uText = QLineEdit()

pLabel = QLabel("Password:")
self.pText = QLineEdit()

okButton = QPushButton()
okButton.setText("OK")
okButton.clicked.connect(self.add)

frame = QFrame(self)

formLayout = QFormLayout(frame)
formLayout.addRow(iLabel, self.iText)
formLayout.addRow(uLabel, self.uText)
formLayout.addRow(pLabel, self.pText)
formLayout.addRow(okButton, okButton)

self.exec_()

def add(self):
ipv4 = self.iText.text()
username = self.uText.text()
password = self.pText.text()

print ipv4, username, password

anda_skoa
16th April 2015, 20:06
The pattern for a modal dialog is usually this

1. create dialog instance
2. call exec() on that instance
3. read values using getter methods

Cheers,
_

ecce
16th April 2015, 20:28
Like this?


def openAddDialog(self):
print "running openAddDialog..."
diag = AddDevice()
diag.exec_()
print diag.getIPv4(), diag.getUsername(), diag.getPassword()

Does not seem like a good way to go, the values will be read if the user cancels/aborts the dialog window. This is exactly what I can't get my head around. I want the buttons and it's slots in the dialog class, but the values from the fields should be sent to or read from the MainWindow.

Lykurg
16th April 2015, 21:49
This is a brilliant way to do what you want :D

exec() returns if the dialog was accepted or rejected (= canceled) so just use this information and read or do not read the username etc.