PDA

View Full Version : Implementing event for Qt Designer MainWindow



shadowfax
30th January 2012, 16:11
Hi!

I've got MainWindow form build in Qt Designer. I want to implement some events for this window. I tried to reimplement closeEvent method using code like this:



from PySide import QtCore
from PySide import QtGui
from PySide import QtUiTools

import sys

class TestWin(QtGui.QMainWindow):

def __init__(self, parent=None):

super(TestWin, self).__init__(parent)

loader = QtUiTools.QUiLoader()
uiFile = QtCore.QFile('testForm.ui')
uiFile.open(QtCore.QFile.ReadOnly)

self.mainWindow = loader.load(uiFile)
self.mainWindow.show()

self.mainWindow.closeEvent = self.myCloseEvent

def myCloseEvent(self, event):

print 'Close'
event.accept()

if __name__ == '__main__':

app = QtGui.QApplication(sys.argv)
testApp = TestWin()
app.exec_()



but this code doesn't work. How should I reimplement methods for Qt Designer forms ?

Thanks,
Marcin

wysota
30th January 2012, 16:49
Is there any particular reason why you are using QtUiTools? This is a very nonstandard approach. Apart that your code looks ok (however a bit unorthodox). What do you mean by that it doesn't work?

shadowfax
5th February 2012, 21:48
I use similar code to load ui as those shown in pySide docs. Should I do this in different way ?
For me code looks correct, but when I close the window myCloseEvent isn't invoked.

wysota
6th February 2012, 00:49
You should use pyside-uic to generate python class from the UI file and then use that class from your code. For example like here:
https://github.com/PySide/Examples/tree/master/examples/designer/calculatorform

shadowfax
6th February 2012, 12:38
I know that pyside-uic code will be better for this, but I was curious how to do the same using dynamically loaded ui.

wysota
6th February 2012, 12:49
You have a strange construction. Your class inherits QMainWindow but you show the object loaded with QtUiTools. Are you sure this is what you want?

shadowfax
6th February 2012, 13:37
That's my mistake. I shouldn't inherit QMainWindow in this case. But I don't understand why closeEvent isn't invoked. I overwrite self.mainWindow closeEvent method,but nothing happens when I close main window.

wysota
6th February 2012, 13:53
Maybe you shouldn't rely on print()? What if you invoke event.ignore()? It should prevent the window from being closed. It could also be that you are not overriding the method properly.

shadowfax
6th February 2012, 15:09
If I invoke event.ignore() I can still close window. It looks like closeEvent was not replaced with my custom close event. I think there's something wrong with my way of overriding the event method.