Reputation: 191
I'm trying to set up an app in Linux using PyQt4
designer and I'm struggling to connect signals and slots to it. Right now all I want it to do is connect a button clicked
signal to a custom slot, saveEnergyScheme
which simply prints 'energy list' to the terminal.
I've translated the .ui code for my app to a python class with pyuic4 -w sumcorr.ui > sumcorr_ui.py
. This created a class in the sumcorr_ui.py
module called SumCorr_ui
:
class SumCorr_ui(QtGui.QMainWindow, Ui_SumCorr_ui):
def __init__(self, parent=None, f=QtCore.Qt.WindowFlags()):
QtGui.QMainWindow.__init__(self, parent, f)
self.setupUi(self)
I then made my app as a custom widget and tried to add a simple signal-slot connection to a button to show it works:
from PyQt4 import QtGui, QtCore
from sumcorr_ui import SumCorr_ui
class SumCorr(SumCorr_ui):
def __init__(self):
SumCorr_ui.__init__(self)
self.save_energies_button.clicked.connect(self.saveEnergyScheme)
def saveEnergyScheme(self):
print 'energyList'
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
mySumCorr = QtGui.QMainWindow()
ui = SumCorr()
ui.setupUi(mySumCorr)
mySumCorr.show()
sys.exit(app.exec_())
I expect to get the line 'energy list' when I click the button named save_energies_button
, but nothing happens. Could this be because I haven't built the UI as a widget, but as a main window? Why doesn't it print out??
Upvotes: 1
Views: 1469
Reputation: 102029
Try to add ui.show()
and you'll see that your code is creating two different windows, one should have the signal connected and one doesn't. That's because you are showing only the mySumCorr
window, but you call only setupUi
on it, which does not connect the signal.
When you create the SumCorr
instance, you are creating a window and setting it up, then, by no reason, you do ui.setupUi(mySumCorr)
, which setups the mySumCorr
instance without connecting the signal, and you show this last window.
I believe your code should be like this:
class SumCorr(QtGui.QMainWindow, Ui_SumCorr_ui):
def __init__(self):
SumCorr_ui.__init__(self)
self.setupUi(self)
self.save_energies_button.clicked.connect(self.saveEnergyScheme)
def saveEnergyScheme(self):
print 'energyList'
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
mySumCorr = SumCorr()
mySumCorr.show()
sys.exit(app.exec_())
Note that it doesn't make any sense to have a SumCorr_ui
class, that's because Qt
is a UI library so you are just introducing a worthless level of abstraction. The designer file already gives you an abstraction over the ui layout.
Upvotes: 2