I have taken two comboBoxes i.e., comboBox1 and comboBox_2 and two functions test and test1 and calling them using currentIndexChanged (self.comboBOx1.currentIndexChanged and self.comboBOx_2.currentIndexChanged). When a value is selected from comboBox1 its corresponding function(self.comboBOx1.currentIndexChanged) is called and same for comboBox_2. On selection of value from comboBox1 changes the values in comboBox_2 and its working fine. But the problem I have got here is that at first when I select a value from comboBox1 and comboBox_2 I'm getting the expected values from the called function(printing 'hello'). The second time when I select a value from comboBox1 only test function should be called but here both the functions(test and test1) are getting called and the second function (test1) is getting called twice(printing 'hello' twice) and for third time its getting called four times(printing 'hello' four times). Please can anyone help me with this problem.?
Code:
from PyQt4 import QtCore, QtGui
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.comboBox1 = QtGui.QComboBox(self.centralwidget)
self.comboBox1.setGeometry(QtCore.QRect(310, 150, 171, 31))
self.comboBox1.setObjectName(_fromUtf8("comboBox1"))
self.comboBox1.addItem(_fromUtf8(""))
self.comboBox1.addItem(_fromUtf8(""))
self.comboBox1.addItem(_fromUtf8(""))
self.comboBox1.addItem(_fromUtf8(""))
self.comboBox_2 = QtGui.QComboBox(self.centralwidget)
self.comboBox_2.setGeometry(QtCore.QRect(310, 240, 171, 41))
self.comboBox_2.setObjectName(_fromUtf8("comboBox_2"))
self.comboBox_2.addItem(_fromUtf8(""))
self.comboBox_2.addItem(_fromUtf8(""))
self.comboBox_2.addItem(_fromUtf8(""))
self.comboBox_2.addItem(_fromUtf8(""))
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.comboBox1.setItemText(0, _translate("MainWindow", "select", None))
self.comboBox1.setItemText(1, _translate("MainWindow", "a", None))
self.comboBox1.setItemText(2, _translate("MainWindow", "b", None))
self.comboBox1.setItemText(3, _translate("MainWindow", "c", None))
self.comboBox_2.setItemText(0, _translate("MainWindow", "select", None))
self.comboBox_2.setItemText(1, _translate("MainWindow", "p", None))
self.comboBox_2.setItemText(2, _translate("MainWindow", "q", None))
self.comboBox_2.setItemText(3, _translate("MainWindow", "r", None))
self.comboBox_2.setEnabled(0)
self.comboBox1.currentIndexChanged.connect(self.test)
def test(self):
s = str(self.comboBox1.currentText())
res=['aa','bb','cc','dd']
if (s == "- - select - -"):
self.comboBox_2.setEnabled(0)
self.comboBox_2.setCurrentIndex(0)
elif(len(s)== 0):
self.comboBox_2.setEnabled(1)
self.comboBox_2.clear()
self.comboBox_2.addItem("- - select - -")
self.comboBox_2.addItem("New Checklist")
else:
self.comboBox_2.setEnabled(1)
self.comboBox_2.clear()
self.comboBox_2.addItem("- - select - -")
self.comboBox_2.addItem("New Checklist")
self.comboBox_2.addItems(res)
self.comboBox_2.currentIndexChanged.connect(self.test1)
def test1(self):
print ("Hello")
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_())
To understand the behavior we will use the following examples:
Example 1:
from PyQt4 import QtCore, QtGui
def on_clicked():
print("clicked")
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
button = QtGui.QPushButton("Press me")
for _ in range(4):
button.clicked.connect(on_clicked)
button.show()
sys.exit(app.exec_())
When you press the button it prints 4 times because Qt does not remember if there was already a connection between signal and a function previously, so if there are n connections between the same signal and function they will be invoked n times when the signal is emitted.
Example 2:
from PyQt4 import QtCore, QtGui
def on_currentIndexChanged(ix):
print("currentIndex:", ix)
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
combo = QtGui.QComboBox()
print("currentIndex:", combo.currentIndex())
combo.currentIndexChanged.connect(on_currentIndexChanged)
button_add = QtGui.QPushButton("Add Items")
button_add.clicked.connect(lambda: combo.addItems("1 2 3".split()))
button_clear = QtGui.QPushButton("Clear")
button_clear.clicked.connect(combo.clear)
w = QtGui.QWidget()
lay = QtGui.QVBoxLayout(w)
for widget in (combo, button_add, button_clear):
lay.addWidget(widget)
w.show()
sys.exit(app.exec_())
The default currentIndex of the QComboBox is -1, when you add items this changes to the currentIndex of 0, and when you clean the QComboBox the currentIndex reverts to -1. So when you add or clean the items, the currentIndexChanged signal is emitted.
Based on the above, I will explain the behavior that you point out: When a new currentIndex is selected in the QCombobox 1 the test method is invoked and if it enters the else statement after cleaning and adding the items you make the first connection, if the same thing is repeated now as there is a connection, the currentIndexChanged signal is emitted twice (one for clear() and another for addItems()) and you also create a second connection, if it is repeated again, the signal is emitted 4 times (1 clear() x 2 connections + 1 addItems() x 2 connections).
Solution:
Make the connection in a function that is invoked only once.
So that the clear() signal and addItems() do not emit the currentIndexChanged signal you must use blockSignals().
As an additional point it is recommended not to modify the code generated by Qt Designer, it is advisable to create another class that uses the initial class as an interface, in addition to using the decoration #QtCore.pyqtSlot().
from PyQt4 import QtCore, QtGui
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.comboBox1 = QtGui.QComboBox(self.centralwidget)
self.comboBox1.setGeometry(QtCore.QRect(310, 150, 171, 31))
self.comboBox1.setObjectName(_fromUtf8("comboBox1"))
self.comboBox1.addItem(_fromUtf8(""))
self.comboBox1.addItem(_fromUtf8(""))
self.comboBox1.addItem(_fromUtf8(""))
self.comboBox1.addItem(_fromUtf8(""))
self.comboBox_2 = QtGui.QComboBox(self.centralwidget)
self.comboBox_2.setGeometry(QtCore.QRect(310, 240, 171, 41))
self.comboBox_2.setObjectName(_fromUtf8("comboBox_2"))
self.comboBox_2.addItem(_fromUtf8(""))
self.comboBox_2.addItem(_fromUtf8(""))
self.comboBox_2.addItem(_fromUtf8(""))
self.comboBox_2.addItem(_fromUtf8(""))
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.comboBox1.setItemText(0, _translate("MainWindow", "select", None))
self.comboBox1.setItemText(1, _translate("MainWindow", "a", None))
self.comboBox1.setItemText(2, _translate("MainWindow", "b", None))
self.comboBox1.setItemText(3, _translate("MainWindow", "c", None))
self.comboBox_2.setItemText(0, _translate("MainWindow", "select", None))
self.comboBox_2.setItemText(1, _translate("MainWindow", "p", None))
self.comboBox_2.setItemText(2, _translate("MainWindow", "q", None))
self.comboBox_2.setItemText(3, _translate("MainWindow", "r", None))
class MainWindow(QtGui.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setupUi(self)
self.comboBox_2.setEnabled(False)
self.comboBox1.currentIndexChanged[str].connect(self.test)
self.comboBox_2.currentIndexChanged.connect(self.test1)
#QtCore.pyqtSlot(str)
def test(self, s):
res=['aa','bb','cc','dd']
if s == "- - select - -":
self.comboBox_2.setEnabled(False)
self.comboBox_2.setCurrentIndex(0)
elif not s:
self.comboBox_2.setEnabled(True)
self.comboBox_2.blockSignals(True)
self.comboBox_2.clear()
self.comboBox_2.addItem("- - select - -")
self.comboBox_2.addItem("New Checklist")
self.comboBox_2.blockSignals(False)
else:
self.comboBox_2.setEnabled(True)
self.comboBox_2.blockSignals(True)
self.comboBox_2.clear()
self.comboBox_2.addItem("- - select - -")
self.comboBox_2.addItem("New Checklist")
self.comboBox_2.addItems(res)
self.comboBox_2.blockSignals(False)
#QtCore.pyqtSlot(int)
def test1(self, ix):
print("Hello", ix)
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
Related
This question already has answers here:
Make QLabel clickable
(4 answers)
Closed 4 years ago.
I'm creating a side menu using pyqt4.
I turned the QLabel (burgermenu) into a picture of a burger menu, and I'm having trouble making it clickable.
My intension is that when I click the burgermenu image, the inner frame (innerframe) hides totally, and when I click burgermenu again; the innerframe appears with its content.
How can I achieve that?
Here is my code:
from PyQt4 import QtCore, QtGui
from PyQt4.QtGui import *
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(479, 381)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.outerframe = QtGui.QFrame(self.centralwidget)
self.outerframe.setGeometry(QtCore.QRect(190, 80, 151, 211))
self.outerframe.setFrameShape(QtGui.QFrame.StyledPanel)
self.outerframe.setFrameShadow(QtGui.QFrame.Raised)
self.outerframe.setObjectName(_fromUtf8("outerframe"))
self.burgermenu = QtGui.QLabel(self.outerframe)
self.burgermenu.setGeometry(QtCore.QRect(70, 10, 71, 20))
self.burgermenu.setObjectName(_fromUtf8("burgermenu"))
self.innerframe = QtGui.QFrame(self.outerframe)
self.innerframe.setGeometry(QtCore.QRect(10, 60, 131, 141))
self.innerframe.setFrameShape(QtGui.QFrame.StyledPanel)
self.innerframe.setFrameShadow(QtGui.QFrame.Raised)
self.innerframe.setObjectName(_fromUtf8("innerframe"))
self.widget = QtGui.QWidget(self.innerframe)
self.widget.setGeometry(QtCore.QRect(20, 30, 91, 99))
self.widget.setObjectName(_fromUtf8("widget"))
self.verticalLayout = QtGui.QVBoxLayout(self.widget)
self.verticalLayout.setMargin(0)
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.label_2 = QtGui.QLabel(self.widget)
self.label_2.setObjectName(_fromUtf8("label_2"))
self.verticalLayout.addWidget(self.label_2)
self.dateEdit = QtGui.QDateEdit(self.widget)
self.dateEdit.setObjectName(_fromUtf8("dateEdit"))
self.verticalLayout.addWidget(self.dateEdit)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 479, 22))
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.burgermenu.setText(_translate("MainWindow", "burgermenu", None))
self.burgermenu.setPixmap(QPixmap("/Users/Desktop/menu.png"))
self.label_2.setText(_translate("MainWindow", "Date:", 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_())
Here you can use method name mousePressEvent
self.burgermenu.mousePressEvent = self.dosomething
after that in dosomething method you can call method called hide or show for innerframe.
self.innerframe.hide()
or
self.innerframe.show()
and dont forget to add event as parameter in dosomething
you can overwrite the mousePressEvent of the QLabel like:
def setupClickToggle(self):
def mousePressEvent(*args, **kwargs):
self.innerframe.setVisible(not self.innerframe.isVisible())
self.burgermenu.mousePressEvent = mousePressEvent
and you simply call it once in your init or during startup:
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
setupClickToggle(MainWindow)
MainWindow.show()
how do i change the text of a label until a push button is clicked in pyqt (how do i keep this in loop)
here is the code i tried
from PyQt4 import QtCore, QtGui
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(376, 290)
MainWindow.setMinimumSize(QtCore.QSize(376, 290))
MainWindow.setMaximumSize(QtCore.QSize(376, 290))
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.pushButton = QtGui.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(150, 210, 75, 23))
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.label = QtGui.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(140, 70, 91, 31))
self.label.setObjectName(_fromUtf8("label"))
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.i = 1
while self.pushButton.clicked:
self.count()
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def count(self):
self.i+=1
print self.i
self.label.setText(str(self.i))
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.pushButton.setText(_translate("MainWindow", "PushButton", None))
self.label.setText(_translate("MainWindow", "TextLabel", None))
if __name__ == "__main__":
import sys
app = QtGui.QApplication([])
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
I tried this code but the GUI doesn't show up and goes to a infinite loop.so, how do i loop this code properly
this is the loop part and function i kept
self.i = 1
while self.pushButton.clicked:
self.count()
def count(self):
self.i+=1
print self.i
self.label.setText(str(self.i))
thanks in advance
raajvamsy
The GUI is not friendly with loops since they have the default main loop: app.exec_(), the most recommended in your case is to use a QTimer that starts as soon as the application is shown and stops when you press the button.
I always recommend not to modify the code that generates Qt Designer, it is better to create a new class that implements the logic and use the generated view, all the above I implemented it in the following code:
class MainWindow(QtGui.QMainWindow, Ui_MainWindow):
counter = 0
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.setupUi(self)
timer = QtCore.QTimer(self)
timer.timeout.connect(self.onTimeout)
timer.start(10) # 10 milliseconds
self.pushButton.clicked.connect(timer.stop)
def onTimeout(self):
self.counter += 1
self.label.setText(str(self.counter))
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.
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()
I'm trying to create a UI for an existing python program that I've made.
On the widget, I have two text boxes (QlineEdit) that I want to use to get the information for the program to use, a button and a textbrowser that will hold the output of the program.
I've stumbled upon PyQT4, which I installed using homebrew, and QT Creator. I've created the UI and converted it from a mainwindow.ui to a mainwindow.py and now I'm trying to figure out how to get the text input from the UI text boxes and have the program use it.
I cant figure out how to extract the text from the text boxes(QlineEdit) and store them in variables(strings) that the program can then use.
From my understanding, I should create a new .py file and import mainwindow as well as PyQT4.QtCore and PyQT4.QtGui. I dont know where to go from here so any insight would be helpful.
Also, how can I have the program print out to the textbrowser?
Maybe my approach is flawed and I should rebuild my program around the mainwindow.py file?
I apologize if this is all trivial information but I've never used PyQT or Qt creator.
Here is the code that I got from the the converted .ui to .py:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'mainwindow.ui'
#
# Created: Wed Aug 13 15:25:22 2014
# by: PyQt4 UI code generator 4.11.1
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
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(480, 385)
MainWindow.setWindowOpacity(1.0)
self.centralWidget = QtGui.QWidget(MainWindow)
self.centralWidget.setObjectName(_fromUtf8("centralWidget"))
self.textBrowser = QtGui.QTextBrowser(self.centralWidget)
self.textBrowser.setGeometry(QtCore.QRect(100, 120, 256, 192))
self.textBrowser.setObjectName(_fromUtf8("textBrowser"))
self.widget = QtGui.QWidget(self.centralWidget)
self.widget.setGeometry(QtCore.QRect(150, 10, 156, 97))
self.widget.setObjectName(_fromUtf8("widget"))
self.verticalLayout_2 = QtGui.QVBoxLayout(self.widget)
self.verticalLayout_2.setMargin(0)
self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
self.verticalLayout = QtGui.QVBoxLayout()
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.lineEdit = QtGui.QLineEdit(self.widget)
self.lineEdit.setObjectName(_fromUtf8("lineEdit"))
self.verticalLayout.addWidget(self.lineEdit)
self.lineEdit_2 = QtGui.QLineEdit(self.widget)
self.lineEdit_2.setObjectName(_fromUtf8("lineEdit_2"))
self.verticalLayout.addWidget(self.lineEdit_2)
self.verticalLayout_2.addLayout(self.verticalLayout)
self.pushButton = QtGui.QPushButton(self.widget)
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.verticalLayout_2.addWidget(self.pushButton)
MainWindow.setCentralWidget(self.centralWidget)
self.menuBar = QtGui.QMenuBar(MainWindow)
self.menuBar.setGeometry(QtCore.QRect(0, 0, 480, 22))
self.menuBar.setObjectName(_fromUtf8("menuBar"))
MainWindow.setMenuBar(self.menuBar)
self.mainToolBar = QtGui.QToolBar(MainWindow)
self.mainToolBar.setObjectName(_fromUtf8("mainToolBar"))
MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.mainToolBar)
self.statusBar = QtGui.QStatusBar(MainWindow)
self.statusBar.setObjectName(_fromUtf8("statusBar"))
MainWindow.setStatusBar(self.statusBar)
self.retranslateUi(MainWindow)
QtCore.QObject.connect(self.lineEdit, QtCore.SIGNAL(_fromUtf8("textEdited(QString)")), self.lineEdit.setText)
QtCore.QObject.connect(self.lineEdit_2, QtCore.SIGNAL(_fromUtf8("textEdited(QString)")), self.lineEdit_2.setText)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.lineEdit.setPlaceholderText(_translate("MainWindow", "Enter Case Number", None))
self.lineEdit_2.setPlaceholderText(_translate("MainWindow", "Number of cases", None))
self.pushButton.setText(_translate("MainWindow", "Submit", 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_())
Any information helps. Thanks
The way UI works is that the UI forms the main loop of the program. Here mainwindow.py is your main loop. You can import your classes that you created in your program (lets call it code.py) or just paste that code into you mainwindow.py. Then on button press or some other kind of event, you can call a function that execute the main code of your code.py
To answer your other questions regarding how to use the text and print to the textbrowser try something like this:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'mainwindow.ui'
#
# Created: Wed Aug 13 15:25:22 2014
# by: PyQt4 UI code generator 4.11.1
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
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(480, 385)
MainWindow.setWindowOpacity(1.0)
self.centralWidget = QtGui.QWidget(MainWindow)
self.centralWidget.setObjectName(_fromUtf8("centralWidget"))
self.textBrowser = QtGui.QTextBrowser(self.centralWidget)
self.textBrowser.setGeometry(QtCore.QRect(100, 120, 256, 192))
self.textBrowser.setObjectName(_fromUtf8("textBrowser"))
self.widget = QtGui.QWidget(self.centralWidget)
self.widget.setGeometry(QtCore.QRect(150, 10, 156, 97))
self.widget.setObjectName(_fromUtf8("widget"))
self.verticalLayout_2 = QtGui.QVBoxLayout(self.widget)
self.verticalLayout_2.setMargin(0)
self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
self.verticalLayout = QtGui.QVBoxLayout()
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.lineEdit = QtGui.QLineEdit(self.widget)
self.lineEdit.setObjectName(_fromUtf8("lineEdit"))
self.verticalLayout.addWidget(self.lineEdit)
self.lineEdit_2 = QtGui.QLineEdit(self.widget)
self.lineEdit_2.setObjectName(_fromUtf8("lineEdit_2"))
self.verticalLayout.addWidget(self.lineEdit_2)
self.verticalLayout_2.addLayout(self.verticalLayout)
self.pushButton = QtGui.QPushButton(self.widget)
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.verticalLayout_2.addWidget(self.pushButton)
MainWindow.setCentralWidget(self.centralWidget)
self.menuBar = QtGui.QMenuBar(MainWindow)
self.menuBar.setGeometry(QtCore.QRect(0, 0, 480, 22))
self.menuBar.setObjectName(_fromUtf8("menuBar"))
MainWindow.setMenuBar(self.menuBar)
self.mainToolBar = QtGui.QToolBar(MainWindow)
self.mainToolBar.setObjectName(_fromUtf8("mainToolBar"))
MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.mainToolBar)
self.statusBar = QtGui.QStatusBar(MainWindow)
self.statusBar.setObjectName(_fromUtf8("statusBar"))
MainWindow.setStatusBar(self.statusBar)
self.retranslateUi(MainWindow)
QtCore.QObject.connect(self.lineEdit, QtCore.SIGNAL(_fromUtf8("textEdited(QString)")), self.lineEdit.setText)
QtCore.QObject.connect(self.lineEdit_2, QtCore.SIGNAL(_fromUtf8("textEdited(QString)")), self.lineEdit_2.setText)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.lineEdit.setPlaceholderText(_translate("MainWindow", "Enter Case Number", None))
self.lineEdit_2.setPlaceholderText(_translate("MainWindow", "Number of cases", None))
self.pushButton.setText(_translate("MainWindow", "Submit", None))
# Call a function when the button "Submit" is pressed
self.pushButton.clicked.connect(self.OnSubmit)
def OnSubmit(self):
# On submit do the necessary
# here I take the text from the LineEdits that you have
# (ie your Case Number, and number of Cases)
# and print them to the textbrowser below
text = self.lineEdit.text() + ' ' + self.lineEdit_2.text()
self.textBrowser.append(text)
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 can find some basic tutorials here: http://zetcode.com/gui/pyqt4/ that can help you understand the properties of your QtGui objects.