I have a simple python QT multiplication program. There are 3 fields, first random number(read only), second random number(read only) and third line edit for user to input result. If first * second = result then show Right Label, else show Wrong Label. I would like to replace exit button with play again button, so when the user press it, to regenerate random numbers and clear all result labels and user try again.
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_Form(object):
def setupUi(self, Form):
Form.setObjectName(_fromUtf8("Form"))
Form.resize(650, 644)
self.label_71 = QtGui.QLabel(Form)
self.label_71.setGeometry(QtCore.QRect(70, 20, 481, 41))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Andika"))
font.setPointSize(26)
self.label_71.setFont(font)
self.label_71.setObjectName(_fromUtf8("label_71"))
self.layoutWidget = QtGui.QWidget(Form)
self.layoutWidget.setGeometry(QtCore.QRect(200, 570, 221, 29))
self.layoutWidget.setObjectName(_fromUtf8("layoutWidget"))
self.horizontalLayout_51 = QtGui.QHBoxLayout(self.layoutWidget)
self.horizontalLayout_51.setMargin(0)
self.horizontalLayout_51.setObjectName(_fromUtf8("horizontalLayout_51"))
self.pushButton_2 = QtGui.QPushButton(self.layoutWidget)
self.pushButton_2.setObjectName(_fromUtf8("pushButton_2"))
self.pushButton_2.clicked.connect(self.exit_)
self.horizontalLayout_51.addWidget(self.pushButton_2)
self.pushButton = QtGui.QPushButton(self.layoutWidget)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.pushButton.setFont(font)
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.pushButton.clicked.connect(self.praxis)
self.horizontalLayout_51.addWidget(self.pushButton)
### Line Edit 1 - 2 ###
self.count = 124
self.list_x1 = []
self.list_y1 = []
for i in range(10):
self.x1 = randint(2,9)
self.list_x1.append(self.x1)
self.ln1 = "self.lineEdit1_" + str(i)
self.ln1 = QtGui.QLineEdit(Form)
self.ln1.setText(str(self.x1))
self.ln1.setReadOnly(True)
self.ln1.setGeometry(QtCore.QRect(74, self.count, 40, 26))
self.ln1.setAlignment(QtCore.Qt.AlignCenter)
self.ln1.setObjectName(_fromUtf8("lineEdit"))
self.y1 = randint(2,9)
self.list_y1.append(self.y1)
self.ln2 = "self.lineEdit2_" + str(i)
self.ln2 = QtGui.QLineEdit(Form)
self.ln2.setText(str(self.y1))
self.ln2.setReadOnly(True)
self.ln2.setGeometry(QtCore.QRect(140, self.count, 40, 26))
self.ln2.setAlignment(QtCore.Qt.AlignCenter)
self.ln2.setObjectName(_fromUtf8("lineEdit_2"))
self.count += 35
#Εισαγωγή 1ης στήλης
self.count = 124
self.ln3_value = []
for i in range(10):
self.ln3 = "self.lineEdit3_" + str(i)
self.ln3_value.append(self.ln3)
self.ln3_value[i] = QtGui.QLineEdit(Form)
self.ln3_value[i].setGeometry(QtCore.QRect(206, self.count, 40, 26))
self.ln3_value[i].setAlignment(QtCore.Qt.AlignCenter)
self.ln3_value[i].setObjectName(_fromUtf8("lineEdit_3"))
self.count += 35
### Line Edit 3- 4 ###
self.count = 124
self.list_x2 = []
self.list_y2 = []
for i in range(10):
self.x2 = randint(2,9)
self.list_x2.append(self.x2)
self.ln4 = "self.lineEdit4_" + str(i)
self.ln4 = QtGui.QLineEdit(Form)
self.ln4.setText(str(self.x2))
self.ln4.setReadOnly(True)
self.ln4.setGeometry(QtCore.QRect(348, self.count, 40, 26))
self.ln4.setAlignment(QtCore.Qt.AlignCenter)
self.ln4.setObjectName(_fromUtf8("lineEdit_4"))
self.y2 = randint(2,9)
self.list_y2.append(self.y2)
self.ln5 = "self.lineEdit5_" + str(i)
self.ln5 = QtGui.QLineEdit(Form)
self.ln5.setText(str(self.y2))
self.ln5.setReadOnly(True)
self.ln5.setGeometry(QtCore.QRect(414, self.count, 40, 26))
self.ln5.setAlignment(QtCore.Qt.AlignCenter)
self.ln5.setObjectName(_fromUtf8("lineEdit_5"))
self.count += 35
#Εισαγωγή 2ης στήλης
self.count = 124
self.ln6_value = []
for i in range(10):
self.ln6 = "self.lineEdit5_" + str(i)
self.ln6_value.append(self.ln3)
self.ln6_value[i] = QtGui.QLineEdit(Form)
self.ln6_value[i].setGeometry(QtCore.QRect(480, self.count, 40, 26))
self.ln6_value[i].setAlignment(QtCore.Qt.AlignCenter)
self.ln6_value[i].setObjectName(_fromUtf8("lineEdit_6"))
self.count += 35
### / Line Edit 1 - 4 ###
### Labels 1 - 6 ###
self.lbl1_count = 119
for i in range(10):
self.lbl_1 = "self.label1_" + str(i)
self.lbl_1 = QtGui.QLabel(Form)
self.lbl_1.setGeometry(QtCore.QRect(120, self.lbl1_count, 14, 34))
self.lbl_1.setText(_translate("Form", "X", None))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Andika"))
font.setPointSize(16)
self.lbl_1.setFont(font)
self.lbl_1.setObjectName(_fromUtf8("label"))
self.lbl1_count += 35
self.lbl2_count = 119
for i in range(10):
self.lbl_2 = "self.label2_" + str(i)
self.lbl_2 = QtGui.QLabel(Form)
self.lbl_2.setGeometry(QtCore.QRect(186, self.lbl2_count, 14, 34))
self.lbl_2.setText(_translate("Form", "=", None))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Andika"))
font.setPointSize(16)
self.lbl_2.setFont(font)
self.lbl_2.setObjectName(_fromUtf8("label_2"))
self.lbl2_count += 35
self.lbl3_list = []
self.lbl3_count = 119
for i in range(10):
self.lbl_3 = "self.label3_" + str(i)
self.lbl3_list.append(self.lbl_3)
self.lbl3_list[i] = QtGui.QLabel(Form)
self.lbl3_list[i].setGeometry(QtCore.QRect(252, self.lbl3_count, 80, 34))
self.lbl3_list[i].setText(_translate("Form", "?", None))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Andika"))
font.setPointSize(14)
self.lbl3_list[i].setFont(font)
self.lbl3_list[i].setObjectName(_fromUtf8("label_3"))
self.lbl3_count += 35
self.lbl4_count = 119
for i in range(10):
self.lbl_4 = "self.label2_" + str(i)
self.lbl_4 = QtGui.QLabel(Form)
self.lbl_4.setGeometry(QtCore.QRect(394, self.lbl4_count, 14, 34))
self.lbl_4.setText(_translate("Form", "X", None))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Andika"))
font.setPointSize(16)
self.lbl_4.setFont(font)
self.lbl_4.setObjectName(_fromUtf8("label_2"))
self.lbl4_count += 35
self.lbl5_count = 119
for i in range(10):
self.lbl_5 = "self.label5_" + str(i)
self.lbl_5 = QtGui.QLabel(Form)
self.lbl_5.setGeometry(QtCore.QRect(460, self.lbl5_count, 14, 34))
self.lbl_5.setText(_translate("Form", "=", None))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Andika"))
font.setPointSize(16)
self.lbl_5.setFont(font)
self.lbl_5.setObjectName(_fromUtf8("label_5"))
self.lbl5_count += 35
self.lbl6_list = []
self.lbl6_count = 119
for i in range(10):
self.lbl_6 = "self.label6_" + str(i)
self.lbl6_list.append(self.lbl_6)
self.lbl6_list[i] = QtGui.QLabel(Form)
self.lbl6_list[i].setGeometry(QtCore.QRect(526, self.lbl6_count, 80, 34))
self.lbl6_list[i].setText(_translate("Form", "?", None))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Andika"))
font.setPointSize(14)
self.lbl6_list[i].setFont(font)
self.lbl6_list[i].setObjectName(_fromUtf8("label_6"))
self.lbl6_count += 35
### / Labels 1 - 6 ###
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(_translate("Form", "Multiplication", None))
self.label_71.setText(_translate("Form", "Multiplication", None))
self.pushButton_2.setText(_translate("Form", "Exit", None))
self.pushButton.setText(_translate("Form", "Check", None))
def praxis(self):
self.lbl3_count = 119
for i in range(10):
self.val = self.ln3_value[i]
self.val2 = self.ln6_value[i]
self.get_val = self.val.text()
self.get_val2 = self.val2.text()
self.get_val_str = str(self.get_val)
self.get_val2_str = str(self.get_val2)
self.summary = self.list_y1[i] * self.list_x1[i]
self.summary2 = self.list_y2[i] * self.list_x2[i]
self.summary_int = str(self.summary)
self.summary_int2 = str(self.summary2)
if self.summary_int == self.get_val_str:
self.lbl3_list[i].setText(_translate("Form", "Σωστό!", None))
self.lbl3_list[i].setStyleSheet('color: green')
else:
self.lbl3_list[i].setText(_translate("Form", "Λάθος!", None))
self.lbl3_list[i].setStyleSheet('color: red')
if self.summary_int2 == self.get_val2_str:
self.lbl6_list[i].setText(_translate("Form", "Σωστό!", None))
self.lbl6_list[i].setStyleSheet('color: green')
else:
self.lbl6_list[i].setText(_translate("Form", "Λάθος!", None))
self.lbl6_list[i].setStyleSheet('color: red')
def exit_(self):
import sys
sys.exit()
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
Form = QtGui.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_())
Related
I'm new to pyqt and trying to make a degrees converter application. Now I want to make the text resizable, when I resize MainWindow.
The code:
from PyQt6 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(QtWidgets.QMainWindow):
def resizeEvent(self, event):
print("Window has been resized")
QtWidgets.QMainWindow.resizeEvent(self, event)
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(305, 250)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Policy.Preferred, QtWidgets.QSizePolicy.Policy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())
MainWindow.setSizePolicy(sizePolicy)
MainWindow.setMinimumSize(QtCore.QSize(305, 250))
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("../../../../Users/Midgetfucker/Downloads/temperature.png"), QtGui.QIcon.Mode.Normal, QtGui.QIcon.State.Off)
MainWindow.setWindowIcon(icon)
MainWindow.setAutoFillBackground(False)
MainWindow.setDocumentMode(False)
self.centralwidget = QtWidgets.QWidget(parent=MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.gridLayout_3 = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout_3.setObjectName("gridLayout_3")
self.lineEdit_input = QtWidgets.QLineEdit(parent=self.centralwidget)
self.lineEdit_input.setStyleSheet("")
self.lineEdit_input.setLocale(QtCore.QLocale(QtCore.QLocale.Language.Russian, QtCore.QLocale.Country.Russia))
self.lineEdit_input.setObjectName("lineEdit_input")
self.gridLayout_3.addWidget(self.lineEdit_input, 0, 1, 1, 1)
self.label_fahrenheit = QtWidgets.QLabel(parent=self.centralwidget)
font = QtGui.QFont()
font.setPointSize(8)
font.setBold(True)
font.setWeight(75)
self.label_fahrenheit.setFont(font)
self.label_fahrenheit.setObjectName("label_fahrenheit")
self.gridLayout_3.addWidget(self.label_fahrenheit, 0, 0, 1, 1)
self.plainTextEdit_output = QtWidgets.QPlainTextEdit(parent=self.centralwidget)
self.plainTextEdit_output.viewport().setProperty("cursor", QtGui.QCursor(QtCore.Qt.CursorShape.ArrowCursor))
self.plainTextEdit_output.setFocusPolicy(QtCore.Qt.FocusPolicy.NoFocus)
self.plainTextEdit_output.setObjectName("plainTextEdit_output")
self.gridLayout_3.addWidget(self.plainTextEdit_output, 1, 0, 1, 2)
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
self.add_functions()
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "Преобразователь температур"))
self.label_fahrenheit.setText(_translate("MainWindow", "Градусы:"))
def add_functions(self):
self.lineEdit_input.textChanged.connect(self.degrees_changed)
def degrees_changed(self):
self.plainTextEdit_output.setPlainText("")
self.plainTextEdit_output.setStyleSheet("")
degrees = self.lineEdit_input.text()
if degrees == '':
return
degrees = degrees.replace(',', '.')
try:
degrees = float(degrees)
except ValueError:
self.plainTextEdit_output.setPlainText("Некорректный ввод")
self.plainTextEdit_output.setStyleSheet("color: rgb(255, 0, 0);")
self.lineEdit_input.setFocus()
return
f_to_c = round((degrees * 9/5 + 32), 2)
f_to_k = round((degrees - 32) * 5/9 + 273.15, 2)
c_to_f = round((degrees - 32) * 5/9, 2)
c_to_k = round(degrees + 273.15, 2)
k_to_f = round((degrees - 273.15) * 9/5 + 32, 2)
k_to_c = round(degrees - 273.15, 2)
if round(f_to_c) == f_to_c:
f_to_c = int(f_to_c)
if round(f_to_k) == f_to_k:
f_to_k = int(f_to_k)
if round(c_to_f) == c_to_f:
c_to_f = int(c_to_f)
if round(c_to_k) == c_to_k:
c_to_k = int(c_to_k)
if round(k_to_f) == k_to_f:
k_to_f = int(k_to_f)
if round(k_to_c) == k_to_c:
k_to_c = int(k_to_c)
if round(degrees) == degrees:
degrees = int(degrees)
f_to_c = str(f_to_c)
f_to_k = str(f_to_k)
c_to_f = str(c_to_f)
c_to_k = str(c_to_k)
k_to_c = str(k_to_c)
k_to_f = str(k_to_f)
degrees = str(degrees)
self.plainTextEdit_output.setPlainText('°F: \n'
+ degrees + '°F = ' + f_to_c + '°C' + '\n'
+ degrees + '°F = ' + f_to_k + '°K' + '\n\n'
+ '°C: \n'
+ degrees + '°C = ' + c_to_f + '°F' + '\n'
+ degrees + '°C = ' + c_to_k + '°K' + '\n\n'
+ '°K: \n'
+ degrees + '°K = ' + k_to_f + '°F' + '\n'
+ degrees + '°K = ' + k_to_c + '°C')
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec())
I've already tried this, but doesn't work for me. Any hints or ideas pls?
Windows 10
Using Qt Designer with PyCharm
I'm Currently making a TextBased game with pyqt5 and I'm using the designer to make the Windows because it was easier, everything was fine until I tried to find out how to Destroy a single Child window I found some Answers but it didn't Fit my Situation (or I'm just bad at this).
Note: I'm using the Designer to Make the UI
Issue: Couldn't Find an Answer to My Problem Which is Destroying a Child Window (HuntTab) when Hp is lesser than 1
import random
from PyQt5 import QtCore, QtGui, QtWidgets
level = 1
job = "NONE"
df = random.randrange(1, 6, 1)
hpMax = random.randrange(95, 120, 1)
hp = hpMax
exp = 0
expMax = 100
attackMax = random.randrange(4, 7, 1)
attackMin = random.randrange(1, 4, 1)
enemyLevel = random.randrange(1, 4, 1)
enemyHp = enemyLevel * 20 + 20
enemyAttackMax = random.randrange(2, 4, 1) * enemyLevel
enemyAttackMin = random.randrange(1, 3, 1) * enemyLevel
luck = 10
looks = 120
class UiMainWindow(object):
UI = f"<html><head/><body><p>Level: {level}</p><p>Job: {job}</p><p>Health: {hp}</p><p>Attack: {attackMin} - {attackMax}</p><p>Defense: {df}</p><p>Luck: {luck}</p><p>Looks: {looks}</p><p><br/></p></body></html>"
def __init__(self, theMainWindow):
super(UiMainWindow, self).__init__()
self.HuntTab = QtWidgets.QWidget()
self.uiHunt = UiHuntTab(self.HuntTab)
self.centralwidget = QtWidgets.QWidget(theMainWindow)
self.MainWindow = theMainWindow
self.statusbar = QtWidgets.QStatusBar(theMainWindow)
self.menubar = QtWidgets.QMenuBar(theMainWindow)
self.Love = QtWidgets.QPushButton(self.centralwidget)
self.Life = QtWidgets.QPushButton(self.centralwidget)
self.Rule = QtWidgets.QPushButton(self.centralwidget)
self.Hunt = QtWidgets.QPushButton(self.centralwidget)
self.Fight = QtWidgets.QPushButton(self.centralwidget)
self.Shop = QtWidgets.QPushButton(self.centralwidget)
self.MainOutput = QtWidgets.QLabel(self.centralwidget)
self.iniUI()
def iniUI(self):
self.Hunt.clicked.connect(self.CallHutTab)
def CallHutTab(self):
self.uiHunt.setupUi(self.HuntTab)
self.HuntTab.show()
def setupUi(self, theMainWindow):
theMainWindow.setObjectName("MainWindow")
theMainWindow.resize(519, 404)
self.centralwidget.setObjectName("centralwidget")
self.MainOutput.setGeometry(QtCore.QRect(40, 30, 131, 171))
self.MainOutput.setIndent(0)
self.MainOutput.setObjectName("MainOutput")
self.Shop.setGeometry(QtCore.QRect(40, 230, 141, 51))
self.Shop.setObjectName("Shop")
self.Fight.setGeometry(QtCore.QRect(190, 230, 141, 51))
self.Fight.setObjectName("Fight")
self.Hunt.setGeometry(QtCore.QRect(340, 230, 141, 51))
self.Hunt.setObjectName("Hunt")
self.Rule.setGeometry(QtCore.QRect(190, 290, 141, 51))
self.Rule.setObjectName("Rule")
self.Life.setGeometry(QtCore.QRect(340, 290, 141, 51))
self.Life.setObjectName("Life")
self.Love.setGeometry(QtCore.QRect(40, 290, 141, 51))
self.Love.setObjectName("Love")
theMainWindow.setCentralWidget(self.centralwidget)
self.menubar.setGeometry(QtCore.QRect(0, 0, 519, 21))
self.menubar.setObjectName("menubar")
theMainWindow.setMenuBar(self.menubar)
self.statusbar.setObjectName("statusbar")
theMainWindow.setStatusBar(self.statusbar)
self.retranslateUi(theMainWindow)
QtCore.QMetaObject.connectSlotsByName(theMainWindow)
def retranslateUi(self, theMainWindow):
_translate = QtCore.QCoreApplication.translate
theMainWindow.setWindowTitle(_translate("MainWindow", "Fight"))
self.MainOutput.setText(_translate("MainWindow", self.UI))
self.Shop.setText(_translate("MainWindow", "Shop"))
self.Fight.setText(_translate("MainWindow", "Fight"))
self.Hunt.setText(_translate("MainWindow", "Hunt"))
self.Rule.setText(_translate("MainWindow", "Rule"))
self.Life.setText(_translate("MainWindow", "Your Life"))
self.Love.setText(_translate("MainWindow", "Love"))
class UiHuntTab(object):
uiText = f"<html><head/><body><p>Hp: {hp} Exp: {exp}/{expMax} Level: {level}</p><p>Enemy Level: {enemyLevel}</p><p>Enemy Health: {enemyHp}</p><p>Enemy attacks: {enemyAttackMin} - {enemyAttackMax}</p><p><br/></p></body></html>"
def __init__(self, HuntTab):
super(UiHuntTab, self).__init__()
self.HuntPotions = QtWidgets.QPushButton(HuntTab)
self.HuntHide = QtWidgets.QPushButton(HuntTab)
self.HuntDefend = QtWidgets.QPushButton(HuntTab)
self.HuntAttack = QtWidgets.QPushButton(HuntTab)
self.HuntTabOutput = QtWidgets.QLabel(HuntTab)
self.iniUi()
def iniUi(self):
self.HuntAttack.clicked.connect(self.Attack)
self.HuntHide.clicked.connect(self.Hide)
def Attack(self):
global hp
global enemyHp
global exp
if hp > 0:
attack = random.randrange(attackMin, attackMax + 1, 1)
enAttack = random.randrange(enemyAttackMin, enemyAttackMax + 1, 1)
hp -= enAttack
enemyHp -= attack
if enemyHp < 1:
exp += enemyLevel * 20
self.NewEnemy()
if exp >= expMax:
self.LevelUp()
uiText = f"<html><head/><body><p>Hp: {hp} Exp: {exp}/{expMax} Level: {level}</p><p>Enemy Level: {enemyLevel}</p><p>Enemy Health: {enemyHp}</p><p>Enemy attacks: {enemyAttackMin} - {enemyAttackMax}</p><p><br/></p></body></html>"
self.HuntTabOutput.setText(uiText)
if hp < 1:
hp = 0
# Death Death Death Death Death Death Death Death
def Hide(self):
global hp
if hp > 0:
hp += 5
if hp >= hpMax:
hp = hpMax
prob = random.randrange(1, 11, 1)
if prob == 5:
hp -= random.randrange(enemyAttackMin, enemyAttackMax, 1)
uiText = f"<html><head/><body><p>Hp: {hp} Exp: {exp}/{expMax} Level: {level}</p><p>Enemy Level: {enemyLevel}</p><p>Enemy Health: {enemyHp}</p><p>Enemy attacks: {enemyAttackMin} - {enemyAttackMax}</p><p><br/></p></body></html>"
self.HuntTabOutput.setText(uiText)
def LevelUp(self):
global level
global attackMax
global attackMin
global expMax
global exp
global hpMax
global hp
level += 1
expMax = (level - 1) * 200
hpMax += 20
hp = hpMax
attackMax += random.randrange(1, 3, 1)
attackMin += random.randrange(1, 3, 1)
exp = 0
uiText = f"<html><head/><body><p>Hp: {hp} Exp: {exp}/{expMax} Level: {level}</p><p>Enemy Level: {enemyLevel}</p><p>Enemy Health: {enemyHp}</p><p>Enemy attacks: {enemyAttackMin} - {enemyAttackMax}</p><p><br/></p></body></html>"
self.HuntTabOutput.setText(uiText)
def NewEnemy(self):
global enemyLevel
global enemyHp
global enemyAttackMax
global enemyAttackMin
enemyLevel = random.randrange(1, 4, 1) * level
enemyHp = enemyLevel * 20 + 20
enemyAttackMax = random.randrange(2, 4, 1) * enemyLevel
enemyAttackMin = random.randrange(1, 3, 1) * enemyLevel
uiText = f"<html><head/><body><p>Hp: {hp} Exp: {exp}/{expMax} Level: {level}</p><p>Enemy Level: {enemyLevel}</p><p>Enemy Health: {enemyHp}</p><p>Enemy attacks: {enemyAttackMin} - {enemyAttackMax}</p><p><br/></p></body></html>"
self.HuntTabOutput.setText(uiText)
def setupUi(self, HuntTab):
HuntTab.setObjectName("HuntTab")
HuntTab.resize(379, 263)
self.HuntTabOutput.setGeometry(QtCore.QRect(30, 30, 150, 101))
self.HuntTabOutput.setObjectName("HuntTabOutput")
self.HuntAttack.setGeometry(QtCore.QRect(30, 140, 91, 41))
self.HuntAttack.setObjectName("HuntAttack")
self.HuntDefend.setGeometry(QtCore.QRect(140, 140, 91, 41))
self.HuntDefend.setObjectName("HuntDefend")
self.HuntHide.setGeometry(QtCore.QRect(250, 140, 91, 41))
self.HuntHide.setObjectName("HuntHide")
self.HuntPotions.setGeometry(QtCore.QRect(140, 190, 91, 41))
self.HuntPotions.setObjectName("HuntPotions")
self.retranslateUi(HuntTab)
QtCore.QMetaObject.connectSlotsByName(HuntTab)
def retranslateUi(self, HuntTab):
_translate = QtCore.QCoreApplication.translate
HuntTab.setWindowTitle(_translate("HuntTab", "Hunt"))
self.HuntTabOutput.setText(_translate("HuntTab", self.uiText))
self.HuntAttack.setText(_translate("HuntTab", "Attack"))
self.HuntDefend.setText(_translate("HuntTab", "Defend"))
self.HuntHide.setText(_translate("HuntTab", "Hide"))
self.HuntPotions.setText(_translate("HuntTab", "Potions"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = UiMainWindow(MainWindow)
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
It Was Easier than I Expected, In the class UiHuntTab and In __init__ I just Added self.HuntTabWindow = HuntTab And when i want to close the HuntTab i only needed to call self.HuntTabWindow.close()
class UiHuntTab(object):
def __init__(self, HuntTab):
super(UiHuntTab, self).__init__()
self.HuntTabWindow = HuntTab
self.HuntPotions = QtWidgets.QPushButton(HuntTab)
self.HuntHide = QtWidgets.QPushButton(HuntTab)
self.HuntDefend = QtWidgets.QPushButton(HuntTab)
self.HuntAttack = QtWidgets.QPushButton(HuntTab)
self.HuntTabOutput = QtWidgets.QLabel(HuntTab)
self.iniUi()
a
if hp < 1:
self.HuntTabWindow.close()
And if I Wanted to Close the MainWindow self.MainWindow = MainWindow and self.MainWindow.close()
In PyQt5, I am using the model view to display a table. The model is the QAbstractTableModel, and I want to background color say row 0. The coloring works, but all rows get colored, instead of the row that I specified. Also, when I change to Qt.Background role, I get some "tickbox" in my cell that I don't want. I guess, that it is my understanding of what actually happen in QAbstractTableModel's def data part that prevents me from achieve the desired effect.
This is my code snippet part as I have already tried. Note the status 1 and status 2 are actually True or False in my case. If True, this entire row should be colored as background green, else it should stay white.
#Make some dummy data
tabledata = list()
tabledata.append(('item 1', 'amount 1', 'price 1', 'status 1'))
tabledata.append(('item 2', 'amount 2', 'price 2', 'status 2'))
#The self.model below is QAbstractTableModel subclassed
self.model.modelTableData = tabledata
#try set data for just one cell
self.model.setData(self.model.index(0,0), QtCore.Qt.BackgroundRole)
self.model.layoutChanged.emit()
Then in my QAbstractTableModel class, I have the following in def data
class TableModel(QtCore.QAbstractTableModel):
def __init__(self, parent, header, tabledata):
#inhert from QAbstractTableModel
QtCore.QAbstractTableModel.__init__(self, parent)
self.modelTableData = tabledata
self.header = header
def rowCount(self, parent):
return len(self.modelTableData)
def columnCount(self, parent):
return len(self.header)
def data(self, index, role):
if not index.isValid():
return None
if role == QtCore.Qt.BackgroundRole:
print('Qt.BackgroundRole at ' + str(index.row()))
return QtCore.QVariant(QtGui.QColor(QtCore.Qt.green))
print('Not Qt.BackgroundRole at ' + str(index.row()))
return self.modelTableData[index.row()][index.column()]
def headerData(self, col, orientation, role):
if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
return self.header[col]
return None
I have googled on similar examples and studied this one in particular
https://python-forum.io/Thread-Change-color-of-a-row-of-a-QTableView
What they seems to do is
if role == QtCore.Qt.BackgroundRole and "something more":
#then do something
It is this "something more" that I don't know how to parse into the def data method. Ideally it should be my row data status 1 that either can be True or False, but my understanding is that def data part is actually returning the data for the viewer?
Also, I get confused about that in my code, when I executed the print, it seems that even though I stated in my data that only one cell at QModelIndex (0,0) is set to green, the next row is also set to green. What is the reason for this behaviour?
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'main_v00.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
import POSTools as tool
import json
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1680, 1050)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.cb_OrderList = QtWidgets.QComboBox(self.centralwidget)
self.cb_OrderList.setGeometry(QtCore.QRect(160, 30, 111, 31))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(2)
sizePolicy.setHeightForWidth(self.cb_OrderList.sizePolicy().hasHeightForWidth())
self.cb_OrderList.setSizePolicy(sizePolicy)
self.cb_OrderList.setObjectName("cb_OrderList")
self.le_NewTable = QtWidgets.QLineEdit(self.centralwidget)
self.le_NewTable.setGeometry(QtCore.QRect(30, 30, 113, 35))
self.le_NewTable.setObjectName("le_NewTable")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(30, 10, 60, 16))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(14)
self.label.setFont(font)
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(self.centralwidget)
self.label_2.setGeometry(QtCore.QRect(170, 10, 60, 16))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(14)
self.label_2.setFont(font)
self.label_2.setObjectName("label_2")
self.le_ItemName = QtWidgets.QLineEdit(self.centralwidget)
self.le_ItemName.setGeometry(QtCore.QRect(30, 100, 171, 35))
self.le_ItemName.setObjectName("le_ItemName")
self.le_ItemAmount = QtWidgets.QLineEdit(self.centralwidget)
self.le_ItemAmount.setGeometry(QtCore.QRect(220, 100, 113, 35))
self.le_ItemAmount.setObjectName("le_ItemAmount")
self.le_UnitPrice = QtWidgets.QLineEdit(self.centralwidget)
self.le_UnitPrice.setGeometry(QtCore.QRect(350, 100, 113, 35))
self.le_UnitPrice.setObjectName("le_UnitPrice")
self.label_3 = QtWidgets.QLabel(self.centralwidget)
self.label_3.setGeometry(QtCore.QRect(30, 70, 101, 21))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(14)
self.label_3.setFont(font)
self.label_3.setObjectName("label_3")
self.label_4 = QtWidgets.QLabel(self.centralwidget)
self.label_4.setGeometry(QtCore.QRect(220, 70, 101, 21))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(14)
self.label_4.setFont(font)
self.label_4.setObjectName("label_4")
self.label_5 = QtWidgets.QLabel(self.centralwidget)
self.label_5.setGeometry(QtCore.QRect(350, 70, 101, 21))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(14)
self.label_5.setFont(font)
self.label_5.setObjectName("label_5")
self.label_6 = QtWidgets.QLabel(self.centralwidget)
self.label_6.setGeometry(QtCore.QRect(480, 70, 101, 21))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(14)
self.label_6.setFont(font)
self.label_6.setObjectName("label_6")
self.tableView = QtWidgets.QTableView(self.centralwidget)
self.tableView.setGeometry(QtCore.QRect(30, 150, 711, 461))
self.tableView.setObjectName("tableView")
self.pb_remove = QtWidgets.QPushButton(self.centralwidget)
self.pb_remove.setGeometry(QtCore.QRect(750, 250, 151, 101))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(18)
self.pb_remove.setFont(font)
self.pb_remove.setObjectName("pb_remove")
self.pb_receipt = QtWidgets.QPushButton(self.centralwidget)
self.pb_receipt.setGeometry(QtCore.QRect(590, 620, 151, 101))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(18)
self.pb_receipt.setFont(font)
self.pb_receipt.setObjectName("pb_receipt")
self.label_TotalPrice = QtWidgets.QLabel(self.centralwidget)
self.label_TotalPrice.setGeometry(QtCore.QRect(480, 100, 121, 35))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(18)
self.label_TotalPrice.setFont(font)
self.label_TotalPrice.setObjectName("label_TotalPrice")
self.le_Discount = QtWidgets.QLineEdit(self.centralwidget)
self.le_Discount.setGeometry(QtCore.QRect(610, 100, 131, 35))
self.le_Discount.setObjectName("le_Discount")
self.label_7 = QtWidgets.QLabel(self.centralwidget)
self.label_7.setGeometry(QtCore.QRect(610, 70, 101, 21))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(14)
self.label_7.setFont(font)
self.label_7.setObjectName("label_7")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(750, 150, 151, 101))
font = QtGui.QFont()
font.setFamily("Arial")
font.setPointSize(18)
self.pushButton.setFont(font)
self.pushButton.setObjectName("pushButton")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 1680, 22))
self.menubar.setObjectName("menubar")
self.menuMore_Options = QtWidgets.QMenu(self.menubar)
self.menuMore_Options.setObjectName("menuMore_Options")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.actionCount_Up = QtWidgets.QAction(MainWindow)
self.actionCount_Up.setObjectName("actionCount_Up")
self.menuMore_Options.addSeparator()
self.menuMore_Options.addAction(self.actionCount_Up)
self.menubar.addAction(self.menuMore_Options.menuAction())
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
MainWindow.setTabOrder(self.le_NewTable, self.cb_OrderList)
MainWindow.setTabOrder(self.cb_OrderList, self.le_ItemName)
MainWindow.setTabOrder(self.le_ItemName, self.le_ItemAmount)
MainWindow.setTabOrder(self.le_ItemAmount, self.le_UnitPrice)
MainWindow.setTabOrder(self.le_UnitPrice, self.le_Discount)
MainWindow.setTabOrder(self.le_Discount, self.pushButton)
MainWindow.setTabOrder(self.pushButton, self.pb_remove)
MainWindow.setTabOrder(self.pb_remove, self.pb_receipt)
MainWindow.setTabOrder(self.pb_receipt, self.tableView)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.label.setText(_translate("MainWindow", "Order"))
self.label_2.setText(_translate("MainWindow", "Order List"))
self.label_3.setText(_translate("MainWindow", "Item Name"))
self.label_4.setText(_translate("MainWindow", "Item Amount"))
self.label_5.setText(_translate("MainWindow", "Unit Price"))
self.label_6.setText(_translate("MainWindow", "Price"))
self.pb_remove.setText(_translate("MainWindow", "Remove"))
self.pb_receipt.setText(_translate("MainWindow", "Receipt"))
self.label_TotalPrice.setText(_translate("MainWindow", "0"))
self.label_7.setText(_translate("MainWindow", "Discount [%]"))
self.pushButton.setText(_translate("MainWindow", "Print Kitchen"))
self.menuMore_Options.setTitle(_translate("MainWindow", "More Options"))
self.actionCount_Up.setText(_translate("MainWindow", "Count Up"))
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super(MainWindow,self).__init__()
self.setupUi(self)
#Start by reading in the menu items
self.URL_MenuDB = "somewhere"
self.path_OrderDB = "somewhere"
header, menudb = tool.load_MenuDB(self.URL_MenuDB)
self.MenuHeader = header
#Prepare the completer by first creating the model
self.completermodel = QtGui.QStandardItemModel()
for item in menudb:
row = list()
for col in item:
cell = QtGui.QStandardItem(str(col))
row.append(cell)
self.completermodel.appendRow(row)
self.completer = QtWidgets.QCompleter()
self.completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
self.completer.setCompletionColumn(0)
self.completer.setModel(self.completermodel)
self.completer.setFilterMode(QtCore.Qt.MatchContains)
self.completer.activated[QtCore.QModelIndex].connect(self.onActivated)
self.le_ItemName.setCompleter(self.completer)
#Setup model view
self.TableViewHeader = ['Item', 'Qty', 'Price', 'Print status']
self.TableData = list()
self.model = TableModel(self, header = self.TableViewHeader, tabledata = self.TableData)
self.model.layoutChanged.emit()
self.tableView.setModel(self.model)
#Upon program starts up, check if OrderDB.txt exists
status, AllTables = tool.importOrderDB(self.path_OrderDB)
if status is True: #OrderDB.txt exists
#check if there is incomplete orders
self.AllTables = AllTables
#A list of all active tables
tablenames = tool.getincompleteOrder(AllTables)
if tablenames:
#update the list of tablenames into drop down list
self.cb_OrderList.clear()
self.cb_OrderList.addItems(tablenames)
#get the index of the current active tablename
self.cb_OrderList.currentText()
#Define what happens when the user press enter og return for item amount
self.le_ItemAmount.returnPressed.connect(self.ItemAmountEnterKeyPress)
#If enter is pressed at unit price, it also connects with self.ItemAmountEnterKeyPress
self.le_UnitPrice.returnPressed.connect(self.ItemAmountEnterKeyPress)
#Define what happens when input table edit field is activated
self.le_NewTable.returnPressed.connect(self.input_newTable)
def input_newTable(self): #When the user create a new order
if not self.le_NewTable.text():
return
else:
#check if OrderDB already exists, if not one will be created. If exists is True, AllTables will be returned
status, AllTables, tablename, nameclash = tool.ExistOrderDB(self.path_OrderDB, self.le_NewTable.text().strip())
if nameclash is True:
tool.msgbox(self,'Bord navn eksisterer. Valg et nyt!')
self.le_NewTable.clear()
return
if status is False: #OrderDB.txt has just been created, and AllTables containing the tableName is returned
self.AllTables = AllTables
#Sort all the incomplete tables from All Tables and return the sorted tablename as pandas DataFrame
tablename = tool.getincompleteOrder(AllTables)
#insert the tablename as list to drop down list
self.cb_OrderList.clear()
self.cb_OrderList.addItems(tablename)
self.le_NewTable.clear()
else: #OrderDB.txt exists, continue to create the new table
#create the tabledict
tabledict = tool.CreateTableDict(self.le_NewTable.text())
self.AllTables.append(tabledict)
#save to data base
tool.saveOrderDB(self.path_OrderDB, self.AllTables)
tablename = tabledict["Name"]
#get a list of all incomplete order names
ordernames = tool.getincompleteOrder(self.AllTables)
self.cb_OrderList.clear()
self.cb_OrderList.addItems(ordernames)
index = self.cb_OrderList.findText(tablename, QtCore.Qt.MatchFixedString)
#set the drop down list to the current active index
self.cb_OrderList.setCurrentIndex(index)
#Set focus to item field
self.le_ItemName.setFocus()
self.le_NewTable.clear()
def ItemAmountEnterKeyPress(self): #insert the item into the table and update the data base behind the scene
if not self.cb_OrderList.currentText():
tool.msgbox(self, 'Select an order first')
return
else:
#Update the selected item into the AllTable
#Do a match to see if self.selected matches the fields
inputtext = self.le_ItemName.text()
if inputtext.strip() == self.selected[0]:
#the selected is the same as what appears in the field. Check the remaining fields
qty = tool.isfloat(self.le_ItemAmount.text())
price = tool.isfloat(self.le_UnitPrice.text())
if qty is not False and price is not False:
#submit the fields to be input into the modelview
index = tool.getTableDict(self)
#Do the visualization
price = [item for item in self.AllTables[index]["orderPrice"]]
totalprice = sum(price)
self.TableData = list(
zip(self.AllTables[index]['itemName'],
self.AllTables[index]['orderQty'],
price,
self.AllTables[index]['PrintStatus_send2kitchen']
))
#Update into the model
tabledata = list()
tabledata.append(('item 1', 'amount 1', 'price 1', 'status 1'))
tabledata.append(('item 2', 'amount 2', 'price 2', 'status 2'))
self.model.modelTableData = tabledata
#self.model.modelTableData = self.TableData
#try set data for just one cell
self.model.setData(self.model.index(0,0),
QtCore.Qt.BackgroundRole)
self.model.layoutChanged.emit()
#tool.plotTable(self, totalprice)
#clear
self.clearInputFields()
self.le_ItemName.setFocus()
else: #the item in the fields is different from self.selected, ask the user to try again
tool.msgbox(self, 'Item er ikke korrekt valgt, prøv igen.')
self.clearInputFields(self)
self.le_ItemName.setFocus()
return
else: #User has not selected from the list
tool.msgbox(self,'Prøv igen. Du skal vælge fra listen når du indsætter item')
self.clearInputFields(self)
self.le_ItemName.setFocus()
return
def clearInputFields(self):
self.le_ItemName.clear()
self.le_ItemAmount.clear()
self.le_UnitPrice.clear()
#QtCore.pyqtSlot(QtCore.QModelIndex)
def onActivated(self, index):
self.selected = list()
for i in range(0, len(self.MenuHeader) +1):
self.selected.append(index.sibling(index.row(),i).data())
#display the selected item in the editfield
self.le_UnitPrice.setText(self.selected[3])
#change focus to amount
self.le_ItemAmount.setFocus()
class TableModel(QtCore.QAbstractTableModel):
def __init__(self, parent, header, tabledata):
#inhert from QAbstractTableModel
QtCore.QAbstractTableModel.__init__(self, parent)
self.modelTableData = tabledata
self.header = header
def rowCount(self, parent):
return len(self.modelTableData)
def columnCount(self, parent):
return len(self.header)
def data(self, index, role):
if not index.isValid():
return None
if role == QtCore.Qt.BackgroundRole:
return QtCore.QVariant(QtGui.QColor(QtCore.Qt.green))
return self.modelTableData[index.row()][index.column()]
def headerData(self, col, orientation, role):
if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
return self.header[col]
return None
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
The expected outcome is only the specified row get colored. Also, the tick mark at each cell that I assume is related to Qt.Background is removed.
Thanks!
The logic of the data() method is to filter the information, in this case I will use a dictionary also considering that you want the complete row to be painted then save a QPersistentModel associated to the chosen row but to column 0, finally the method setData() does nothing by default so you have to override.
The error that indicates about the checkboxes is because you are returning the text for any other role like the Qt::CheckStateRole, instead you must filter the information as I already indicated
from PyQt5 import QtCore, QtGui, QtWidgets
class TableModel(QtCore.QAbstractTableModel):
def __init__(self, parent, header, tabledata):
QtCore.QAbstractTableModel.__init__(self, parent)
self.modelTableData = tabledata
self.header = header
self.background_colors = dict()
def rowCount(self, parent=QtCore.QModelIndex()):
return len(self.modelTableData)
def columnCount(self, parent=QtCore.QModelIndex()):
return len(self.header)
def data(self, index, role):
if not index.isValid():
return None
if (
0 <= index.row() < self.rowCount()
and 0 <= index.column() < self.columnCount()
):
if role == QtCore.Qt.BackgroundRole:
ix = self.index(index.row(), 0)
pix = QtCore.QPersistentModelIndex(ix)
if pix in self.background_colors:
color = self.background_colors[pix]
return color
elif role == QtCore.Qt.DisplayRole:
return self.modelTableData[index.row()][index.column()]
def setData(self, index, value, role):
if not index.isValid():
return False
if (
0 <= index.row() < self.rowCount()
and 0 <= index.column() < self.columnCount()
):
if role == QtCore.Qt.BackgroundRole and index.isValid():
ix = self.index(index.row(), 0)
pix = QtCore.QPersistentModelIndex(ix)
self.background_colors[pix] = value
return True
return False
def headerData(self, col, orientation, role):
if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
return self.header[col]
return None
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = QtWidgets.QTableView()
header = ["Item", "Qty", "Price", "Print status"]
tabledata = [
("item 1", "amount 1", "price 1", "status 1"),
("item 2", "amount 2", "price 2", "status 2"),
]
model = TableModel(None, header, tabledata)
model.setData(
model.index(0, 0), QtGui.QColor(QtCore.Qt.green), QtCore.Qt.BackgroundRole
)
w.setModel(model)
w.show()
sys.exit(app.exec_())
#eyllanesc thanks so much for giving me another opportunity to learn. It helped by realizing that I need to filter the information. Also, I realized that I actually don't need to setData for this to work. Below is how I have rewritten the code based on your comments and example. I have only one question left, the way I implemented the def data below, doesn't it make the code very expensive, in the sense that the enumerator loop needs to be executed for identifying which rows need to be colored every time the def data is called?
class TableModel(QtCore.QAbstractTableModel):
def __init__(self, parent, header, tabledata):
#inhert from QAbstractTableModel
QtCore.QAbstractTableModel.__init__(self, parent)
self.modelTableData = tabledata
self.header = header
def rowCount(self, parent):
return len(self.modelTableData)
def columnCount(self, parent):
return len(self.header)
def data(self, index, role):
if not index.isValid():
return None
if role == QtCore.Qt.CheckStateRole:
return None
#get rows to be colored
rowscolor = list()
for item in enumerate(self.modelTableData):
if item[1][-1] == False:
rowscolor.append(item[0])
if role == QtCore.Qt.BackgroundRole and index.row() in rowscolor:
return QtCore.QVariant(QtGui.QColor(QtCore.Qt.green))
return self.modelTableData[index.row()][index.column()]
def headerData(self, col, orientation, role):
if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
return self.header[col]
return None
I have problem with connecting two functions to each other in my small program.
I am using PyQt5 and PyPDF2 modules.I would like to link two pdf files into one.
In my program I have 3 buttons:
btnPlik1 - browse 1st file (connected to function openFile1)
btnPlik2 - browse 2nd file (connected to function openFile2)
btnPlik3 - 'start' - run program (connected to function laczeniePdf)
Functions work separately but when I would like to connect them by clicking 'Start'(btnPlik3) my program crashes. Below is my code:
def openFile1(self):
pathFileName, _ = QtWidgets.QFileDialog.getOpenFileName(None, 'Wybierz plik', '', 'pdf(*.pdf)')
print("PathFileName-'{}', \n_-'{}'".format(pathFileName, _))
if pathFileName:
print("Wybrany plik: ", pathFileName)
g = open(pathFileName, 'rb')
return g
def openFile2(self):
pathFileName, _ = QtWidgets.QFileDialog.getOpenFileName(None, 'Wybierz plik', '', 'pdf(*.pdf)')
print("PathFileName-'{}', \n_-'{}'".format(pathFileName, _))
if pathFileName:
print("Wybrany plik: ", pathFileName)
h = open(pathFileName, 'rb')
return h
def laczeniePdf(self,g, h):
readerLinkPage1 = PyPDF2.PdfFileReader(open(g, 'rb'))
readerLinkPage2 = PyPDF2.PdfFileReader(open(h, 'rb'))
writerLinkPage = PyPDF2.PdfFileWriter()
OutputFile = open('FinalOutput.pdf', 'wb')
writerLinkPage.appendPagesFromReader(readerLinkPage1)
writerLinkPage.appendPagesFromReader(readerLinkPage2)
writerLinkPage.write(OutputFile)
OutputFile.close()
I am looking forward for your hints and advises
EDIT:
Here is code of class we are talking about(it is separate window in my program)
class Ui_PolaczPliki(object):
def setupUi(self, PolaczPliki):
PolaczPliki.setObjectName("PolaczPliki")
PolaczPliki.resize(295, 113)
self.btnPlik1 = QtWidgets.QPushButton(PolaczPliki)
self.btnPlik1.setGeometry(QtCore.QRect(30, 40, 91, 41))
self.btnPlik1.setObjectName("btnPlik1")
self.btnPlik1.clicked.connect(self.openFile1)
self.btnPlik2 = QtWidgets.QPushButton(PolaczPliki)
self.btnPlik2.setGeometry(QtCore.QRect(160, 40, 91, 41))
self.btnPlik2.setObjectName("btnPlik2")
self.btnPlik2.clicked.connect(self.openFile2)
self.btnPlik3 = QtWidgets.QPushButton(PolaczPliki)
self.btnPlik3.setGeometry(QtCore.QRect(80, 80, 40, 20))
self.btnPlik3.setObjectName("btnPlik3")
self.btnPlik3.clicked.connect(self.laczeniePdf)
self.label = QtWidgets.QLabel(PolaczPliki)
self.label.setGeometry(QtCore.QRect(50, 10, 47, 13))
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(PolaczPliki)
self.label_2.setGeometry(QtCore.QRect(180, 10, 47, 13))
self.label_2.setObjectName("label_2")
self.retranslateUi(PolaczPliki)
QtCore.QMetaObject.connectSlotsByName(PolaczPliki)
def retranslateUi(self, PolaczPliki):
_translate = QtCore.QCoreApplication.translate
PolaczPliki.setWindowTitle(_translate("PolaczPliki", "Polacz pliki"))
self.btnPlik1.setText(_translate("PolaczPliki", "Dodaj"))
self.btnPlik2.setText(_translate("PolaczPliki", "Dodaj"))
self.btnPlik3.setText(_translate("PolaczPliki", "Start"))
self.label.setText(_translate("PolaczPliki", "Plik nr 1"))
self.label_2.setText(_translate("PolaczPliki", "Plik nr 2"))
def openFile1(self):
pathFileName, _ = QtWidgets.QFileDialog.getOpenFileName(None, 'Wybierz plik', '', 'pdf(*.pdf)')
print("PathFileName-'{}', \n_-'{}'".format(pathFileName, _))
if pathFileName:
print("Wybrany plik: ", pathFileName)
g = open(pathFileName, 'rb')
return g
def openFile2(self):
pathFileName, _ = QtWidgets.QFileDialog.getOpenFileName(None, 'Wybierz plik', '', 'pdf(*.pdf)')
print("PathFileName-'{}', \n_-'{}'".format(pathFileName, _))
if pathFileName:
print("Wybrany plik: ", pathFileName)
h = open(pathFileName, 'rb')
return h
def laczeniePdf(self, g,h):
readerLinkPage1 = PyPDF2.PdfFileReader(g)
readerLinkPage2 = PyPDF2.PdfFileReader(h)
writerLinkPage = PyPDF2.PdfFileWriter()
OutputFile = open('FinalOutput.pdf', 'wb')
writerLinkPage.appendPagesFromReader(readerLinkPage1)
writerLinkPage.appendPagesFromReader(readerLinkPage2)
writerLinkPage.write(OutputFile)
OutputFile.close()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
ex = Ui_MainWindow()
w = QtWidgets.QMainWindow()
ex.setupUi(w)
w.show()
sys.exit(app.exec_())
Try it:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
import PyPDF2
class Ui_PolaczPliki(object):
def __init__(self): # +++
self.file_1 = None # +++
self.file_2 = None # +++
def setupUi(self, PolaczPliki):
PolaczPliki.setObjectName("PolaczPliki")
PolaczPliki.resize(600, 150)
self.btnPlik1 = QtWidgets.QPushButton(PolaczPliki)
self.btnPlik1.setGeometry(QtCore.QRect(30, 40, 91, 41))
self.btnPlik1.setObjectName("btnPlik1")
self.btnPlik1.clicked.connect(self.openFile1)
self.btnPlik2 = QtWidgets.QPushButton(PolaczPliki)
self.btnPlik2.setGeometry(QtCore.QRect(300, 40, 91, 41))
self.btnPlik2.setObjectName("btnPlik2")
self.btnPlik2.clicked.connect(self.openFile2)
self.btnPlik3 = QtWidgets.QPushButton(PolaczPliki)
self.btnPlik3.setGeometry(QtCore.QRect(165, 90, 91, 41))
self.btnPlik3.setObjectName("btnPlik3")
self.btnPlik3.clicked.connect(lambda: self.laczeniePdf(self.file_1, self.file_2)) # +++
self.label = QtWidgets.QLabel(PolaczPliki)
self.label.setGeometry(QtCore.QRect(30, 10, 47, 13))
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(PolaczPliki)
self.label_2.setGeometry(QtCore.QRect(300, 10, 47, 13))
self.label_2.setObjectName("label_2")
self.retranslateUi(PolaczPliki)
QtCore.QMetaObject.connectSlotsByName(PolaczPliki)
def retranslateUi(self, PolaczPliki):
_translate = QtCore.QCoreApplication.translate
PolaczPliki.setWindowTitle(_translate("PolaczPliki", "Polacz pliki"))
self.btnPlik1.setText(_translate("PolaczPliki", "Dodaj Plik nr 1"))
self.btnPlik2.setText(_translate("PolaczPliki", "Dodaj Plik nr 2"))
self.btnPlik3.setText(_translate("PolaczPliki", "Start"))
self.label.setText(_translate("PolaczPliki", "Plik nr 1"))
self.label_2.setText(_translate("PolaczPliki", "Plik nr 2"))
def openFile1(self):
pathFileName, _ = QtWidgets.QFileDialog.getOpenFileName(None, 'Wybierz plik', '', 'pdf(*.pdf)')
print("PathFileName-'{}', \n_-'{}'".format(pathFileName, _))
if pathFileName:
print("\nWybrany plik: ", pathFileName)
self.file_1 = pathFileName # +++
self.label.setText("{}".format(self.file_1)) # +++
self.label.adjustSize() # +++
#g = open(pathFileName, 'rb')
#print("\ng = open(pathFileName, 'rb') =`{}`, \ntype g =`{}` ".format(g, type(g)))
#return g
def openFile2(self):
pathFileName, _ = QtWidgets.QFileDialog.getOpenFileName(None, 'Wybierz plik', '', 'pdf(*.pdf)')
print("PathFileName-'{}', \n_-'{}'".format(pathFileName, _))
if pathFileName:
print("\nWybrany plik: ", pathFileName)
self.file_2 = pathFileName # +++
self.label_2.setText("{}".format(self.file_2)) # +++
self.label_2.adjustSize() # +++
#h = open(pathFileName, 'rb')
#print("\nh = open(pathFileName, 'rb') =`{}`, \ntype h =`{}` ".format(h, type(h)))
#return h
def laczeniePdf(self, file_1, file_2): # +++
g = open(file_1, 'rb') # +++
h = open(file_2, 'rb') # +++
readerLinkPage1 = PyPDF2.PdfFileReader(g)
readerLinkPage2 = PyPDF2.PdfFileReader(h)
writerLinkPage = PyPDF2.PdfFileWriter()
OutputFile = open('FinalOutput.pdf', 'wb')
writerLinkPage.appendPagesFromReader(readerLinkPage1)
writerLinkPage.appendPagesFromReader(readerLinkPage2)
writerLinkPage.write(OutputFile)
OutputFile.close()
print("\n g=`{}` + h=`{}` !!!".format(file_1, file_2))
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
ex = Ui_PolaczPliki() #Ui_MainWindow() # +++
w = QtWidgets.QMainWindow()
ex.setupUi(w)
w.show()
sys.exit(app.exec_())
I have seen some information posted about this, but everything seems to be with PyQt4 not PyQt5 and I'm not sure if there is a difference. I couldn't get anything to work.
What I want to do is have the program update a QLabel after the user inputs text into it and saves it. Right now I have the main window, with either a button or a selection from a drop down menu that will pop up a window with the ability to change setpoints.
Now what happens is the user can put in new data, but the code seems to still run and not wait for the user to make a change in the popup. calling my updateSetpoints function before anything changes.
# popups the reactorSetpoints window to change the setpoints for
# the reactor. This is where I am haiving troubles, the code
# continues before the user can input new setpoints
def reactorSetpoints(self):
exPopup = setpointsPopup(self)
self.updateSetpoints()
# just have it update the one value for now
def updateSetpoints(self):
self.pHUpperValue.setText(str(upper_pH))
A button calls reactorSetpoints(self) and popups a new window
import sys
import matplotlib.pyplot as plt
import random
from PyQt5.QtWidgets import QMainWindow, QAction, qApp, QApplication,QLineEdit, QPushButton, QWidget, QDialog, QTextEdit, QLabel, QMenu, QVBoxLayout, QSizePolicy
from PyQt5.QtGui import *
from PyQt5.QtCore import Qt, QTime, QTimer, QRect
from PyQt5 import QtCore
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
debug = True
setPointsChanged = False
versionNumber = 'V0.0.1'
currentState = 'Treatment'
currentCycTime = '2:15:42'
remaningCycTime = '5:44:18'
current_pH = 6.85
current_DO = 1.90
currentTemp = 24.9
lower_pH = 6.95
upper_pH = 7.20
lower_DO = 2.00
def openFile():
if debug == True:
print("Open File")
def saveFile():
if debug == True:
print("Save File")
def saveFileAs():
if debug == True:
print("Save File As...")
def editSysParm():
if debug == True:
print("Edit system parameters")
def reactorParameters():
if debug == True:
print("Edit reactor parameters")
def pHCalibration():
if debug == True:
print("pH Calibration")
def dOCalibration():
if debug == True:
print("DO calibration")
def pumpCalibration():
if debug == True:
print("Pump calibrations")
def editpHSetpoints():
pass
# sets up the setpoints popup window with either the option to save
# new setpoints, or to quit
class setpointsPopup(QDialog):
def __init__(self, parent = None):
super().__init__(parent)
self.initUI()
def initUI(self):
self.setGeometry(100,100,300,300)
self.upH = QLabel('Upper pH: ',self)
self.lpH = QLabel('Lower pH: ',self)
self.lDO = QLabel('Lower DO: ',self)
self.upHE = QLineEdit(self)
self.lpHE = QLineEdit(self)
self.lDOE = QLineEdit(self)
self.upHE.setPlaceholderText(str(upper_pH))
self.lpHE.setPlaceholderText(str(lower_pH))
self.lDOE.setPlaceholderText(str(lower_DO))
self.exitSetpoints = QPushButton('Exit', self)
self.saveSetpoints = QPushButton('Save New Setpoints', self)
self.upH.move(5,5)
self.upHE.move(90,5)
self.lpH.move(5,40)
self.lpHE.move(90,40)
self.lDO.move(5,75)
self.lDOE.move(90,75)
self.exitSetpoints.setGeometry(QRect(5,120,50,30))
self.exitSetpoints.clicked.connect(self.destroy)
self.saveSetpoints.setGeometry(QRect(60,120,150,30))
self.saveSetpoints.clicked.connect(self.verifySetpoints)
self.show()
#verification will be put here to make sure the input is valid
#but for now it will accept anything for ease of testing
def verifySetpoints(self):
global upper_pH
newUpH = self.upHE.text()
upper_pH = float(newUpH)
print(newUpH)
# Main window
class drawMenuBar(QMainWindow):
def __init__(self):
super().__init__()
self.topL = 20
self.top = 40
self.width = 1000
self.height = 500
self.title = ('Batch Reactor Controller ' + versionNumber)
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.topL, self.top, self.width, self.height)
exitAct = QAction('&Exit' , self)
exitAct.setShortcut('Ctrl+Q')
exitAct.setStatusTip('Exit Application')
exitAct.triggered.connect(qApp.quit)
openAct = QAction('&Open', self)
openAct.setShortcut('Ctrl+O')
openAct.setStatusTip('Open File')
openAct.triggered.connect(openFile)
saveAsAct = QAction('&Save As..', self)
saveAsAct.setShortcut('Shift+Ctrl+S')
saveAsAct.setStatusTip('Save as new file')
saveAsAct.triggered.connect(saveFileAs)
saveAct = QAction('Save', self)
saveAct.setStatusTip('Save')
saveAct.setShortcut('Ctrl+S')
saveAct.triggered.connect(saveFile)
systemSetpointsAct = QAction('Preferences', self)
systemSetpointsAct.setStatusTip('Edit system parameters')
systemSetpointsAct.triggered.connect(editSysParm)
reactorSetpointsAct = QAction('Reactor Setpoints', self)
reactorSetpointsAct.setStatusTip('Edit reactor setpoints')
reactorSetpointsAct.triggered.connect(self.reactorSetpoints)
reactorParametersAct = QAction('Reactor Parameters', self)
reactorParametersAct.setStatusTip('Edit batch reactor profiles')
reactorParametersAct.triggered.connect(reactorParameters)
pHCalibrationAct = QAction('pH Calibration', self)
pHCalibrationAct.setStatusTip('pH Calibration')
pHCalibrationAct.triggered.connect(pHCalibration)
dOCalibrationAct = QAction('DO Calibration', self)
dOCalibrationAct.setStatusTip('Dissolved oxygen calibration')
dOCalibrationAct.triggered.connect(dOCalibration)
pumpCalibrationAct = QAction('Pump Calibrations', self)
pumpCalibrationAct.setStatusTip('Pump Calibrations')
pumpCalibrationAct.triggered.connect(pumpCalibration)
menubar = self.menuBar()
self.statusBar()
fileMenu = menubar.addMenu('&File')
editMenu = menubar.addMenu('&Edit')
calibrationMenu = menubar.addMenu('&Calibration')
fileMenu.addAction(openAct)
fileMenu.addAction(saveAct)
fileMenu.addAction(saveAsAct)
fileMenu.addAction(exitAct)
calibrationMenu.addAction(pHCalibrationAct)
calibrationMenu.addAction(dOCalibrationAct)
calibrationMenu.addAction(pumpCalibrationAct)
editMenu.addAction(systemSetpointsAct)
editMenu.addAction(reactorSetpointsAct)
self.reactorTitle = QLabel('<b><u>Reactor 1 Status</u></b>', self)
font = self.reactorTitle.font()
font.setPointSize(20)
self.reactorTitle.setFont(font)
self.reactorTitle.setGeometry(QtCore.QRect(10,30, 250, 45)) #(x, y, width, height)
#pH Label
self.pHLabel = QLabel('<span style="color:blue"><b>pH:</b></span>',self)
font = self.pHLabel.font()
font.setPointSize(22)
self.pHLabel.setFont(font)
self.pHLabel.setGeometry(QtCore.QRect(10,50,100,100))
#displays current pH value
self.currentpH = QLabel('<b>' + str(current_pH) + '</b>', self)
font = self.currentpH.font()
font.setPointSize(22)
self.currentpH.setFont(font)
self.currentpH.setGeometry(QtCore.QRect(60,50,100,100))
#display lowerpH Setpoint
self.pHLowerLabel = QLabel('Lower pH setpoint: ', self)
font = self.pHLowerLabel.font()
font.setPointSize(10)
self.pHLowerLabel.setFont(font)
self.pHLowerLabel.setGeometry(QtCore.QRect(10, 105, 115, 50))
self.pHLowerValue = QLabel('{0:0.2f}'.format(lower_pH), self)
font = self.pHLowerValue.font()
font.setPointSize(10)
self.pHLowerValue.setFont(font)
self.pHLowerValue.setGeometry(QtCore.QRect(120, 105, 50, 50))
#display upper pH setpoint
self.pHUpperLabel = QLabel('Upper pH setpoint: ', self)
font = self.pHUpperLabel.font()
font.setPointSize(10)
self.pHUpperLabel.setFont(font)
self.pHUpperLabel.setGeometry(QtCore.QRect(10, 120, 115, 50))
self.pHUpperValue = QLabel('{0:0.2f}'.format(upper_pH), self)
font = self.pHUpperValue.font()
font.setPointSize(10)
self.pHUpperValue.setFont(font)
self.pHUpperValue.setGeometry(QtCore.QRect(120, 120, 50, 50))
#pH button options
self.pHToGraph = QPushButton('Graph pH', self)
self.pHToGraph.move(10,160)
self.pHToGraph.setToolTip('Show pH in live graph')
self.pHToGraph.clicked.connect(self.displaypHGraph)
self.pHSetpointsButton = QPushButton('Update Setpoints', self)
self.pHSetpointsButton.setGeometry(QtCore.QRect(115, 160, 150, 30))
self.pHSetpointsButton.setToolTip('Edit pH Setpoints')
self.pHSetpointsButton.clicked.connect(self.reactorSetpoints)
self.DOLabel = QLabel('<span style="color:blue"><b>DO:</b></span>',self)
font = self.DOLabel.font()
font.setPointSize(22)
self.DOLabel.setFont(font)
self.DOLabel.setGeometry(QtCore.QRect(10,175,100,100))
self.currentDO = QLabel('<b>' + str(current_DO) + ' mg/L</b>', self)
font = self.currentDO.font()
font.setPointSize(22)
self.currentDO.setFont(font)
self.currentDO.setGeometry(QtCore.QRect(60,175,150,100))
self.DOLowerLabel = QLabel('Lower DO setpoint: ', self)
font = self.DOLowerLabel.font()
font.setPointSize(10)
self.DOLowerLabel.setFont(font)
self.DOLowerLabel.setGeometry(QtCore.QRect(10, 225, 115, 50))
self.DOLowerValue = QLabel('{0:0.2f}'.format(lower_DO) + ' mg/L', self)
font = self.DOLowerValue.font()
font.setPointSize(10)
self.DOLowerValue.setFont(font)
self.DOLowerValue.setGeometry(QtCore.QRect(120, 225, 75, 50))
self.DOToGraph = QPushButton('Graph DO', self)
self.DOToGraph.move(10,260)
self.DOToGraph.setToolTip('Show DO in live graph')
self.DOToGraph.clicked.connect(self.displaypHGraph)
self.tempLabel = QLabel('<span style="color:blue"><b>Temperature:</b></span>',self)
font = self.tempLabel.font()
font.setPointSize(22)
self.tempLabel.setFont(font)
self.tempLabel.setGeometry(QtCore.QRect(10,265,190,100))
self.currentTemp = QLabel('<b>' + str(currentTemp) + '\u2103', self)
font = self.currentTemp.font()
font.setPointSize(22)
self.currentTemp.setFont(font)
self.currentTemp.setGeometry(QtCore.QRect(195,265,150,100))
self.currentStatus = QLabel('<b><u>Other Parameters</u><b>', self)
font = self.currentStatus.font()
font.setPointSize(10)
self.currentStatus.setFont(font)
self.currentStatus.setGeometry(QtCore.QRect(10, 325, 200, 50))
self.currentStatus = QLabel('Current Cycle: ' + '<b>' + currentState + '</b>', self)
font = self.currentStatus.font()
font.setPointSize(10)
self.currentStatus.setFont(font)
self.currentStatus.setGeometry(QtCore.QRect(10, 340, 200, 50))
self.currentCycleTime = QLabel('Current Cycle Time (HH:MM:SS): ' + '<b>' + currentCycTime + '</b>', self)
font = self.currentCycleTime.font()
font.setPointSize(10)
self.currentCycleTime.setFont(font)
self.currentCycleTime.setGeometry(QtCore.QRect(10, 355, 250, 50))
self.remaningCycleTime = QLabel('Remaning Cycle Time (HH:MM:SS): ' + '<b>' + remaningCycTime + '</b>', self)
font = self.remaningCycleTime.font()
font.setPointSize(10)
self.remaningCycleTime.setFont(font)
self.remaningCycleTime.setGeometry(QtCore.QRect(10, 370, 275, 50))
self.show()
# just a dummy graph that I got off a tutorial, it works for what
# i need it to do for now
def displaypHGraph(self):
print("Display pH")
self.m = LinePlot(self, width = 16, height = 9)
self.m.setGeometry(QtCore.QRect(300,40,660,370))
self.m.show()
def displayDOGraph(self):
pass
# was playing with how to update labels here. Just a counter
# that counts up the value from the initial
# this will eventually be replaced with sensor inputs
def updatepH(self):
global current_pH
global lower_pH
global upper_pH
current_pH = current_pH + 0.01
display_pH = '{0:0.2f}'.format(current_pH)
if current_pH < lower_pH:
self.currentpH.setText('<span style="color:red"><b>' + str(display_pH) + '</b></span>')
elif current_pH > upper_pH:
self.currentpH.setText('<span style="color:red"><b>' + str(display_pH) + '</b></span>')
else:
self.currentpH.setText('<span style="color:black"><b>' + str(display_pH) + '<b></span>')
# same thing as with the updatepH function except for DO
def updateDO(self):
global current_DO
global lower_DO
current_DO = current_DO + 0.01
display_DO = '{0:0.2f}'.format(current_DO)
if current_DO < lower_DO:
self.currentDO.setText('<span style = "color:red"><b>' + str(display_DO) + ' mg/L</b></span>')
else:
self.currentDO.setText('<span style = "color:black"><b>' + str(display_DO)+ ' mg/L</b></span>')
# popups the reactorSetpoints window to change the setpoints for
# the reactor. This is where I am haiving troubles, the code
# continues before the user can input new setpoints
def reactorSetpoints(self):
exPopup = setpointsPopup(self)
self.updateSetpoints()
# just have it update the one value for now
def updateSetpoints(self):
self.pHUpperValue.setText(str(upper_pH))
# dummy plot, was learning how to put a matplotlib
# it works for now
class LinePlot(FigureCanvas):
def __init__(self, parent=None, width=16, height=9, dpi=100):
fig = Figure(figsize=(width, height), dpi=dpi)
self.axes = fig.add_subplot(111)
FigureCanvas.__init__(self, fig)
self.setParent(parent)
FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding,QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
self.plot()
def plot(self):
data = [6.89,6.90,6.91,6.92,6.93,6.92,6.96,6.99,7.12,7.14,6.98,6.93,7.01,6.90,7.11,7.21,7.13,6.99]
ax = self.figure.add_subplot(111)
ax.plot(data, 'r-')
ax.set_title('pH')
ax.set_xlabel('Time')
ax.set_ylabel('pH Value')
self.draw()
def main():
app = QApplication(sys.argv)
ex = drawMenuBar()
timer = QTimer()
timer.timeout.connect(ex.updatepH)
timer.timeout.connect(ex.updateDO)
timer.start(1000)
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
so all of this works, except the only way I can get the label to update is to close out of the setpoints popup and reopen it. What is a good way to update it upon exiting of the popup window?
Thanks.