Question

I'm new to PyQt though I know python a bit.. I wanted to Qt designer for GUI programming since it'll make my job easier. I've taken a simple dialog in Qt designer and converted using pyuic4.

from PyQt4 import QtCore, QtGui

class Ui_Form1(object):
    def setupUi(self, Form1):
        Form1.setObjectName("Form1")
        Form1.resize(495, 364)
        self.listWidget = QtGui.QListWidget(Form1)
        self.listWidget.setGeometry(QtCore.QRect(60, 100, 221, 111))
        self.listWidget.setObjectName("listWidget")
        self.lineEdit = QtGui.QLineEdit(Form1)
        self.lineEdit.setGeometry(QtCore.QRect(60, 250, 221, 26))
        self.lineEdit.setObjectName("lineEdit")
        self.pushButton = QtGui.QPushButton(Form1)
        self.pushButton.setGeometry(QtCore.QRect(350, 170, 92, 28))
        self.pushButton.setAutoDefault(False)
        self.pushButton.setObjectName("pushButton")

        self.retranslateUi(Form1)
        QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL("clicked()"), self.listWidget.clear)
        QtCore.QMetaObject.connectSlotsByName(Form1)

    def retranslateUi(self, Form1):
        Form1.setWindowTitle(QtGui.QApplication.translate("Form1", "Form1", None, QtGui.QApplication.UnicodeUTF8))
        self.pushButton.setText(QtGui.QApplication.translate("Form1", "X", None, QtGui.QApplication.UnicodeUTF8))

I want to run this program. How to run this program from this file by importing this? I know it's a very basic question.

Was it helpful?

Solution

You may pass -x parameter to pyuic. It will generate addtional code to make the script executable.


In real application you should better write a subclass of QMainWindow which could look like this:

# Store this code in the file MyMainWindow.py
from PyQt4.QtGui import *

class MyMainWindow(QMainWindow):
    def __init__(self, ui_layout):
        QMainWindow.__init__(self)

        self.ui = ui_layout
        ui_layout.setupUi(self)

And also create a main executable script in the same directory as MyMainWindow.py:

from PyQt4.QtGui import *
from MyMainWindow import *
from Form1 import *             # replace Form1 the name of your generated file
import sys

app = QApplication(sys.argv)

window = MyMainWindow(Ui_Form1())
window.show()

sys.exit(app.exec_())

Then run this last script to launch the program.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top