Extending PyQT4 text editor
Disabled "Save" buttonWhen there is no open file, or no changes the "Save" button should be disabled. In QTDesigner in the Property Editor we can set "enabled" attribute to "False" to disable the button. If Designer can do this so does PyQT4. Used textEdit widget has "textChanged()" signal so this part is easy. In the pushButton docs there is nothing about "enabled", but notice this line (before methods list):
Inherits QAbstractButton.pushButton class inherits QAbstractButton and has its methods. When we go to QAbstractButton docs we wont see any method related to "enabled", but QAbstractButton inherits QWidget, and QWidget has setEnabled() method. So here is the start.py file: I've added the slot with signal connection:
QtCore.QObject.connect(self.ui.editor_window,QtCore.SIGNAL("textChanged()"), self.enable_save)In the file_dialog slot when we add text to the textEdit from file the "textChanged()" signal will be emitted so we have disable the "Save" button after it: An the "Save" button will work as planned.
Save od Discard changesWhen we want to open a file and we didn't saved changes to the current open file a message box should appear asking what to do about those changes - Save, Discard, Cancel. We will use QMessageBox. Go show it we need only: The window needs to be configured. We have to add buttons and some text. But how do we use it? We need to edit file_dialog method and if there are unsaved changes show the message. And how we will know if there are unsaved changes ? If the "Save" button is active (self.ui.button_save.isEnabled()) then we have unsaved changes. So here is start.py: The new part is: We create a QtGui.QMessageBox and then we set the message text (setText), window title (setWindowTitle), icon (setIcon, values are in the docs), and then we add 3 buttons ("Save", "Discard" i "Cancel"). As a second argument we add "role" of the button. Values are in the docs and they are responsible for the order of those buttons. setDetailedText sets detailed message, and after that we run the QMessageBox with exec_(). message.clickedButton() will return a pushButton object of the clicked button. To figure out which one was clicked we can compare buttons text. The Message Box looks like this:
Note: to get English names on the buttons regenerate "edytor.py" class using "edytorEN.ui" and run the application using "startEN.py"