Search code examples
pythonc++qtqt-designerpyuic

Using C++, how can I run a python file in Qt Designer?


I've finally decided to make the transition from WxPython to QT! I'm using Qt Designer5.9, but I'm having issues placing a new slot. My goal is to press a button on the GUI and have a function run that I have written in another python program.

In Qt Designer, I "go to slot", select clicked() and this appears.

mainwindow.cpp

void MainWindow::on_pushButton_2_clicked()
{

}

Which is exactly what I want, but the wrong language! My python is bad enough let alone anything else. So by running this tutorial I know that if I pass through ui->textEdit->append(("Hello World")); I can do something custom, but after converting using pyuic to convert to .py it's not obvious how it's being implemented. My function is easy to import as shown below, I just need to know where to put it.

import myfunction
myfunction()

Can anyone give me an example of what needs to be written in C++ in Qt Designer so I can call my python function after .ui conversion??


Solution

  • I don't know why you need C++, you can do what you want in python. Design your UI in QT Designer. I like to avoid using pyuic, I prefer using the following way, maybe you will find it better. Say your UI file is called something.ui, and you have named your button in QT Designer pushButton_2, then the code in python will be:

    from PyQt4 import QtCore, QtGui, uic
    Ui_somewindow, _ = uic.loadUiType("something.ui") #the path to your UI
    
    class SomeWindow(QtGui.QMainWindow, Ui_somewindow):
        def __init__(self):
            QtGui.QMainWindow.__init__(self)
            Ui_somewindow.__init__(self)
            self.setupUi(self)
            self.pushButton_2.clicked.connect(self.yourFunction)
    
       def yourFunction(self):
            #the function you imported or anything you want to happen when the button is clicked.
    
    if __name__ == "__main__":
        app = QtGui.QApplication(sys.argv)
        window = SomeWindow()
        window.show()
        sys.exit(app.exec_())
    

    Hope this helps!