pyuic4 edytor.ui > edytor.pyAnd I got a file with a "Ui_notepad" class. To start an application using it we need a "special" code. Create a file start.py with: Execute start.py to show the application. Click on "Close" to close it. Now the main part - our own slots. In QT3 we could do that in QTDesigner, but here it looks different. We will edit start.py and add there our code not touching edytor.py code. Here is the modified start.py: Now when you click on "Open File" you'll see "aaaaaaaaaa" in the editor window. It happens because we connect "Open File" button click signal with our slot:
QtCore.QObject.connect(self.ui.button_open,QtCore.SIGNAL("clicked()"), self.file_dialog)Where self.ui is our window object through which we can access the widgets, so self.ui.button_open is the "Open File" button. self.file_dialog is the method name which will be executed when the signal will be emitted. It is important to add our code after self.ui.setupUi(self). As for the custom slot: self.ui.editor_window this is our TextEdit, which has setText method, as described in the docs. That's how you add custom slots to a PyQT4 application :cool:
Now we have to use QFileDialog to select a file. Here is the code: fd.getOpenFileName() will show a File Selection window, which will close after selecting a file (returns path to file), and allowing the rest of the code to execute. It works but not that if we cancel file selection fd.getOpenFileName() will not return a path to a existing file, we will get a bug like:
IOError: [Errno 2] Nie ma takiego pliku ani katalogu: < PyQt4.QtCore.QString object at 0x2b6465569738 >So we have to improve our code: So we can view our files, but we can't save changes. I needed a "Save" button so I edited the ui file in QTDesigner and added a pushButton with "button_save" name. After editing the *ui file we have to recreate the gui class:
pyuic4 edytor.ui > edytor.pyAnd now our application looks like this: We add a slot that saves the file and connect him with a "clicked()" signal of "Save" pushButton: It works but some of you may detect a but - It doesn't support non-ASCII files/characters. So we need to use some UTF-8 help with Python codecs and unicode(): And the text editor is UTF-8 friendly. In the next tutorials I'll show you how to add more features to this editor thus learning more of PyQT4.
Note: to get English names on the buttons regenerate "edytor.py" class using "edytorEN.ui"