[PyQt] Code structure in pyqt
Hans-Peter Jansen
hpj at urpla.net
Mon Apr 11 21:30:31 BST 2011
On Monday 11 April 2011, 20:14:28 Jason Rahm wrote:
> Python 2.7.1 / PyQt 4.8.3 / Qt 4.7.2
>
> Marrying the GUI components to processes that come fairly easy to me
> on the cli is a struggle for me at this point. I have a mainwindow
> and some dialogs, all of which I can open ok and do some processing,
> etc. What's difficult for me is figuring out where to draw the lines
> between application function and GUI control processing. For
> example, I have a main window and one dialog that connects to a
> device for authentication. The dialog has the lineedit widgets for
> collecting the username, password, and host and was designed with
> Designer. Currently, my code looks like this:
>
> class Main(QMainWindow, Ui_mw_Editor):
> def __init__(self):
> QMainWindow.__init__(self)
>
> # This is always the same
> self.setupUi(self)
> # QActions on Editor Menubar / Toolbar
>
> self.actionConnect.triggered.connect(self.connectDialog)
>
> def connectDialog(self):
> self.connectdlg = ConnectDlg()
> self.connectdlg.show()
>
> class ConnectDlg(QDialog, Ui_dia_connect):
> def __init__(self):
> QDialog.__init__(self)
> self.setupUi(self)
>
> self.pb_ok.clicked.connect(self.button_click)
> self.pb_cancel.clicked.connect(self.reject)
>
> def button_click(self):
> self.host = self.cb_hostname.currentText()
> self.uname = self.le_username.text()
> self.upass = self.le_password.text()
> #print "Host is %s, Username is %s, Password is
> %s." % (self.host, self.uname, self.upass)
>
> That works. Now to the questions on approach:
>
> 1. Should I move each dialog's code into a separate file and
> import it to keep the main window code clean?
Depends on your own esthetic demands, no? ROT: If you can imagine to use
this dialog from another module, put in in its own file..
> 2. I'm still unsure how to pass data back from a dialog to the
> main window. If I set the call to the dialog in the main class to a
> variable, would any object I return from the dialog be an attribute
> of that object, or would I need to create n objects for each object
> being returned?
This is exactly, why signals and slots where invented. At the moment a
user connects successfully to the device, you emit, say
LoginSuccess(uname, upass), and connect to this signal in your main
window. (Search for emit in the examples).
> 3. Does the return command destroy the dialog, or do I need to
> have a self.accept before the return? The dialog closes, but I'm not
> sure what's proper to ensure cleanup in the backend.
As long, as you don't set a special flag in your dialogs c'tor
(Qt.WindowFlags(Qt.WA_DeleteOnClose)), it's just hidden, and can be
show()n any time again. Usually, you would check for self.connectdlg
being None before calling the c'tor, which prevents the dialog from
being created over and over again. Alternatively, you call it once at
startup.
Hth,
Pete
More information about the PyQt
mailing list