[GIS] How to connect push button in dock widget form

pyqgispythonqgisqgis-plugins

Following this tutorial as a guide, I created a plugin using the Plugin Builder with the dock widget form. I am now trying to connect a pushButton to a function. The following is a snippet of code:

def __init__(self, iface):
    self.dockwidget.pushButton.clicked.connect(self.test_print)

def test_print(self):
    print 'It works!'

However, I receive an:

error when calling its classFactory() method

I have also tried:

def initGui(self):
    QObject.connect(self.dockwidget.pushButton, SIGNAL("clicked()"), self.test_print)

But then there's an error calling its initGui() method. Any pointers?


Edit:

I have tried the following variations in the run(self) function, I no longer receive errors but nothing is printed in the console:

def run(self):
    #self.dockwidget.connect(self.dockwidget.pushButton,SIGNAL("clicked()"),self.test_print)
    #self.dockwidget.pushButton.clicked.connect(self.test_print)
    QObject.connect(self.dockwidget.ui.pushButton, SIGNAL("clicked()"), self.test_print)

Best Answer

import os

from PyQt4 import QtGui, uic
from PyQt4.QtCore import pyqtSignal

FORM_CLASS, _ = uic.loadUiType(os.path.join(
    os.path.dirname(__file__), 'my_dockwidget_base.ui'))


class myDockWidget(QtGui.QDockWidget, FORM_CLASS):

    closingPlugin = pyqtSignal()

    def __init__(self, parent=None):
        """Constructor."""
        super(myDockWidget, self).__init__(parent)
        # Set up the user interface from Designer.
        # After setupUI you can access any designer object by doing
        # self.<objectname>, and you can use autoconnect slots - see
        # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
        # #widgets-and-dialogs-with-auto-connect
        self.setupUi(self)

    def closeEvent(self, event):
        self.closingPlugin.emit()
        event.accept()

from PyQt4.QtCore import * #QSettings, QTranslator, qVersion, QCoreApplication, Qt
from PyQt4.QtGui import * #QAction, QIcon
from qgis.core import *
# Initialize Qt resources from file resources.py
import resources

# Import the code for the DockWidget
from my_dockwidget import myDockWidget
import os.path

class myPlugin:

    # cutting other methods (__init__, initGui, unload..etc..)
    def run(self):
       if not self.pluginIsActive:
           self.pluginIsActive = True

           # openOtherWin is outside of run method...
           self.dockwidget.but_openOtherWin.clicked.connect(self.openOtherWin)

Related Question