How to connect 2 windows using pyqtSignal in PyQt? - python

I create simple application using 2 windows, and i want connect it with button using pyqtsignal, but when i run the application display information "TypeError: pyqtSignal must be bound to a QObject, not 'Form1'":
from PyQt4 import QtCore, QtGui
import form2
import sys
from functools import partial
from PyQt4.QtCore import pyqtSignal
from lib2to3.fixer_util import String
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Form1(QtGui.QMainWindow):
Form2Signal = pyqtSignal(str, str)
def __init__(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(319, 147)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.bt_form1 = QtGui.QPushButton(self.centralwidget)
self.bt_form1.setGeometry(QtCore.QRect(110, 30, 101, 41))
self.bt_form1.setObjectName(_fromUtf8("bt_form1"))
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 319, 21))
self.menubar.setObjectName(_fromUtf8("menubar"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
self.bt_form1.clicked.connect(self.Form2Signal.emit(String))
MainWindow.setWindowTitle(_translate("MainWindow", "Form_1", None))
self.bt_form1.setText(_translate("MainWindow", "FORM_1", None))
class Form2(QtGui.QMainWindow):
Form1Signal = pyqtSignal(str, str)
def __init__(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(319, 147)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.bt_form2 = QtGui.QPushButton(self.centralwidget)
self.bt_form2.setGeometry(QtCore.QRect(110, 30, 101, 41))
self.bt_form2.setObjectName(_fromUtf8("bt_form2"))
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 319, 21))
self.menubar.setObjectName(_fromUtf8("menubar"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
self.bt_form2.clicked.connect(self.Form1Signal.emit)
MainWindow.setWindowTitle(_translate("MainWindow", "Form_2", None))
self.bt_form2.setText(_translate("MainWindow", "FORM_2", None))
class MainWidget(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWidget, self).__init__(parent)
self.stack = QtGui.QStackedWidget()
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.stack)
self.form1 = Form1(self)
self.form2 = Form2(self)
self.stack.addWidget(self.form1)
self.stack.addWidget(self.form2)
self.form1.Form2Signal.connect(partial(self.stack.setCurrentWidget,self.form2))
self.form2.Form1Signal.connect(partial(self.stack.setCurrentWidget,self.form1))
self.stack.setCurrentWidget(self.form1)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
w = MainWidget()
w.show()
app.exec_()
sys.exit()

Add super(Form1, self).__init__() in __init__ method of Form1 class. Do the same for Form2

Related

How to connect a QPushButton to a function

I want to create a simple program with a PyQt GUI. For this I used Qt Designer, and I made a window with a push-button named OpenImage. Moreover, I have a file named rony.py that has a function show. So I want that when the user clicks the button, the image will appear.
This is my code:
from PyQt4 import QtCore, QtGui
import rony
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(800, 600)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.horizontalLayout = QtGui.QHBoxLayout(self.centralwidget)
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.OpenImage = QtGui.QPushButton(self.centralwidget)
self.OpenImage.setObjectName(_fromUtf8("OpenImage"))
self.horizontalLayout.addWidget(self.OpenImage)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
self.menubar.setObjectName(_fromUtf8("menubar"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.OpenImage.setText(_translate("MainWindow", "PushButton", None))
OpenImage.connect(show()) # Why this line don't work
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
rony.py
from PIL import Image
img = Image.open("pipe.png")
def show():
img.show()
You have to reference the name of your script when calling a function from it. It works as a library:
OpenImage.connect(rony.show())

Dynamically add and sort items in tableview python

Reading data in from a simple dict d={key:['desc',dateadded]}
Goal is to add data into table view and sort by date in the list. Cannot get any data to add when trying to put table on main window.
The issue lies with how I am placing the table on the main window. I have a working widget with table and am now trying to combine the two files. Currently the application crashes. Dont want you to write the code but a nudge in the right direction would be a big help.
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'display.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4.QtGui import (QMainWindow, QApplication)
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def __init__(self):
#app = QApplication(sys.argv)
self.window = QMainWindow()
self.setupUi(self.window)
self.window.show()
self.setmydata()
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(296, 478)
MainWindow.setIconSize(QtCore.QSize(0, 0))
MainWindow.setAnimated(False)
MainWindow.setTabShape(QtGui.QTabWidget.Rounded)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.tableView = QtGui.QTableView(self.centralwidget)
self.tableView.setGeometry(QtCore.QRect(20, 50, 261, 391))
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.tableView.sizePolicy().hasHeightForWidth())
self.tableView.setSizePolicy(sizePolicy)
self.tableView.setEditTriggers(QtGui.QAbstractItemView.AllEditTriggers)
self.tableView.setDragEnabled(True)
self.tableView.setAlternatingRowColors(True)
self.tableView.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)
self.tableView.setSortingEnabled(False)
self.tableView.setObjectName(_fromUtf8("tableView"))
self.pushButton = QtGui.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(20, 10, 121, 31))
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.pushButton_2 = QtGui.QPushButton(self.centralwidget)
self.pushButton_2.setGeometry(QtCore.QRect(160, 10, 121, 31))
self.pushButton_2.setObjectName(_fromUtf8("pushButton_2"))
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 296, 21))
self.menubar.setObjectName(_fromUtf8("menubar"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def setmydata(self):
d={"12345678":["do some stuff here that needs to be in a large cell to wrap text","1"],"12343378":["do stuff","1"]}
self.data = {}
keys=d.keys()
self.data['col1']=keys
self.data['col2']=[]
for key in keys:
self.data['col2'].append(d[key][0])
horHeaders = []
for n, key in enumerate(sorted(self.data.keys())):
horHeaders.append(key)
for m, item in enumerate(self.data[key]):
newitem = QTableWidgetItem(item)
self.setItem(m, n, newitem)
self.setHorizontalHeaderLabels(horHeaders)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.pushButton.setText(_translate("MainWindow", "Add New", None))
self.pushButton_2.setText(_translate("MainWindow", "Save", None))
app = QApplication(sys.argv)
frame = Ui_MainWindow()
#frame.show()
app.exec_()
After digging through the code I found line
self.tableView = QtGui.QTableView(self.centralwidget)
needed to be QTableWidget rather than a View. This allows for me to set values and so on.

How to refresh items in Qcombobox [python]?

I have a list of data which is shown in the Qcombobox (using 'addItems')
Now - if the list is changed by loading data from a file with pushbutton - i don't see the new data in the combobx.
The new data is there (I can print it after loading)
What do I miss?
below is the code for the simplified gui
from PyQt4 import QtCore, QtGui
from PyQt4.QtGui import QFileDialog
import pandas as pd
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def __init__(self):
self.comboData=['None']
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(456, 172)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.comboBox = QtGui.QComboBox(self.centralwidget)
self.comboBox.setGeometry(QtCore.QRect(120, 60, 69, 22))
self.comboBox.setObjectName(_fromUtf8("comboBox"))
self.comboBox.setEditable(True)
self.comboBox.addItems(self.comboData)
self.pushButton = QtGui.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(260, 60, 75, 23))
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.pushButton.clicked.connect(self.load)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 456, 21))
self.menubar.setObjectName(_fromUtf8("menubar"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.pushButton.setText(_translate("MainWindow", "Load", None))
def load(self):
fileName=QFileDialog.getOpenFileName(MainWindow,'Load File')
data_pd=pd.read_csv(fileName,index_col=0,na_filter=False)
self.comboData=list(data_pd.var1)
print(self.comboData)
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
you only load the data to self.comboData but do not load them to self.comboBox.
At the end of
def load(self):
add the following lines:
self.comboBox.clear() # delete all items from comboBox
self.comboBox.addItems(self.comboData) # add the actual content of self.comboData
As the model used by QComboBox emits the dataChanged() signal whenever the data in an item are changed, the combobox is repainted automatically and it is not necessary to update the combobox by
self.comboBox.update()

Pyqt4 MainWindow->Form->Form impossible?

i want to display form after form that is display after mainwindow.
This is my code. I success display form after mainwindow.
but MainWindow->Form->Form not work....
please help my brain
my brain is very hot...
main.py
class main(QtGui.QMainWindow):
def __init__(self,parent=None):
QtGui.QWidget.__init__(self,parent)
self.ui=Ui_MainWindow()
self.ui.setupUi(self)
app=QtGui.QApplication(sys.argv)
myapp=main()
myapp.show()
app.exec_()
mainUI.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'main.ui'
#
# Created: Tue Mar 17 17:24:48 2015
# by: PyQt4 UI code generator 4.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
import thread
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
def start(msg):
while 1:
None
def start2(msg):
while 1:
None
global Form
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(722, 265)
MainWindow.setMinimumSize(QtCore.QSize(722, 265))
MainWindow.setMaximumSize(QtCore.QSize(722, 265))
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(_fromUtf8("image/images.jpg")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
MainWindow.setWindowIcon(icon)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.label = QtGui.QLabel(self.centralwidget)
self.label.setEnabled(True)
self.label.setGeometry(QtCore.QRect(-30, -50, 751, 341))
self.label.setMouseTracking(False)
self.label.setAcceptDrops(False)
self.label.setText(_fromUtf8(""))
self.label.setPixmap(QtGui.QPixmap(_fromUtf8("image/main.png")))
self.label.setObjectName(_fromUtf8("label"))
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 722, 21))
self.menubar.setObjectName(_fromUtf8("menubar"))
self.menu = QtGui.QMenu(self.menubar)
self.menu.setObjectName(_fromUtf8("menu"))
MainWindow.setMenuBar(self.menubar)
self.action = QtGui.QAction(MainWindow)
self.action.setObjectName(_fromUtf8("action"))
self.menu.addAction(self.action)
self.menubar.addAction(self.menu.menuAction())
self.retranslateUi(MainWindow)
QtCore.QObject.connect(self.action, QtCore.SIGNAL(_fromUtf8("triggered()")), self.create_child)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def create_child(self):
#here put the code that creates the new window and shows it.
global Form
Form=QtGui.QWidget()
child = release_Form()
child.setupReleaseUi(Form)
thread.start_new_thread(start,(Form,))
Form.show()
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "Smart Update", None))
self.menu.setTitle(_translate("MainWindow", "릴리즈노트", None))
self.action.setText(_translate("MainWindow", "릴리즈노트", None))
class release_Form(object):
def setupReleaseUi(self, Form):
Form.setObjectName(_fromUtf8("Form"))
Form.resize(499, 406)
self.New = QtGui.QPlainTextEdit(Form)
self.New.setGeometry(QtCore.QRect(20, 20, 104, 301))
self.New.setObjectName(_fromUtf8("New"))
self.Modify = QtGui.QPlainTextEdit(Form)
self.Modify.setGeometry(QtCore.QRect(150, 20, 104, 301))
self.Modify.setObjectName(_fromUtf8("Modify"))
self.Delete = QtGui.QPlainTextEdit(Form)
self.Delete.setGeometry(QtCore.QRect(280, 20, 104, 301))
self.Delete.setObjectName(_fromUtf8("Delete"))
self.pushButton = QtGui.QPushButton(Form)
self.pushButton.setGeometry(QtCore.QRect(410, 70, 75, 23))
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.retranslateUi(Form)
QtCore.QObject.connect(self.New, QtCore.SIGNAL(_fromUtf8("textChanged()")), self.Modify.clear)
QtCore.QObject.connect(self.Modify, QtCore.SIGNAL(_fromUtf8("textChanged()")), self.New.centerCursor)
QtCore.QObject.connect(self.Delete, QtCore.SIGNAL(_fromUtf8("textChanged()")), self.Delete.centerCursor)
QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8("clicked()")), self.create_alert)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(_translate("Form", "Form", None))
def create_alert(self):
global Form
Form1=QtGui.QWidget()
alert_Form.show()
child1 = alert_Form()
child1.setupAlertUi(Form1)
thread.start_new_thread(start2,(Form,))
Form1.show()
class alert_Form(object):
def setupAlertUi(self, Form):
Form.setObjectName(_fromUtf8("Form"))
Form.resize(431, 109)
Form.setMinimumSize(QtCore.QSize(431, 109))
Form.setMaximumSize(QtCore.QSize(431, 109))
self.label = QtGui.QLabel(Form)
self.label.setGeometry(QtCore.QRect(-10, -10, 451, 121))
self.label.setText(_fromUtf8(""))
self.label.setPixmap(QtGui.QPixmap(_fromUtf8("image/alert.png")))
self.label.setScaledContents(True)
self.label.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
self.label.setObjectName(_fromUtf8("label"))
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(_translate("Form", "Alert", None))
you should connect function.
and you call other Form like this
if you want only once call Form, remove thread.
def create_setting(self):
global Dialog
Dialog=QtGui.QDialog()
thread.start_new_thread(start,(Dialog,))
child = settingUI.Ui_Form()
child.setupUi(Dialog)
Dialog.setWindowFlags(Dialog.windowFlags()|QtCore.Qt.WindowSystemMenuHint|QtCore.Qt.WindowMinMaxButtonsHint)
Dialog.show()

Display installation progress in PyQt

I've written a little scrip to run a command for installing
software on ubuntu.Here it is:
from PyQt4 import QtCore, QtGui
from subprocess import Popen,PIPE
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(426, 296)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.btn = QtGui.QPushButton(self.centralwidget)
self.btn.setGeometry(QtCore.QRect(170, 190, 81, 27))
self.btn.setObjectName(_fromUtf8("btn"))
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 426, 25))
self.menubar.setObjectName(_fromUtf8("menubar"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QObject.connect(self.btn, QtCore.SIGNAL(_fromUtf8("clicked()")), self.runcmnd)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def runcmnd(self):
p = Popen('sudo apt-get install leafpad', stdout=PIPE,stderr=PIPE, shell=True)
out, err = p.communicate()
print out
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.btn.setText(_translate("MainWindow", "ok", None))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
Now I want a bar which will display the installation progress. I know that
it can be done using pyqt progress bar but I've no idea how to do that.
A simple way is to run a timer, poll the process's stdout periodically, and update the progress bar accordingly.
class Ui_MainWindow(object):
_timer = None
# ...
def runcmnd(self):
self.p = Popen #...skipped. Note that p is now a member variable
self._timer= QTimer(self)
self._timer.setSingleShot(False)
self._timer.timeout.connect(self.pollProgress)
self._timer.start(1000) # Poll every second; adjust as needed
def pollProgress(self):
output = self.p.stdout.read()
progress = # ...Parse the output and update the progress bar
if progress == 100: # Finished
self._timer.stop()
self._timer = None
Some error-checking will be needed (when the network is faulty, user enters wrong password, etc.), of course.
By the way, Popen('sudo apt-get install leafpad') won't work. You'll need
Popen(['sudo', 'apt-get', 'install', 'leafpad'])
Thank you. Please make it a bit clear for me. I'm just a beginner.Do you mean that, I have to set a timer with an action and then update the progress bar in accordance with the time?This is how I managed the codes according to your suggestion. Give me just a sample script or correct my mistakes please:
class Ui_MainWindow(object):
_timer = None
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(426, 296)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.btn = QtGui.QPushButton(self.centralwidget)
self.btn.setGeometry(QtCore.QRect(170, 190, 81, 27))
self.btn.setObjectName(_fromUtf8("btn"))
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 426, 25))
self.menubar.setObjectName(_fromUtf8("menubar"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QObject.connect(self.btn, QtCore.SIGNAL(_fromUtf8("clicked()")), self.runcmnd)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def runcmnd(self):
self.p = Popen(['sudo', 'apt-get', 'install', 'leafpad'])
self._timer= QtCore.QTimer(self)
self._timer.setSingleShot(False)
self._timer.timeout.connect(self.pollProgress)
self._timer.start(1000) # Poll every second; adjust as needed
def pollProgress(self):
output = self.p.stdout.read()
progress = # ...Parse the output and update the progress bar
if progress == 100: # Finished
self._timer.stop()
self._timer = None

Categories