How to reference PyQt UI elements from around the code? - python

Let's say I have a simple window with three controls: a combo box, a push (toggle) button and a text edit control.
To spice it up, I needed the algorithm to run in a thread (while the toggle is pressed), but I guess the solution to the main problem I have won't be influenced with that
When the toggle button is pressed, I want to read the current ComboBox value and update the TextEdit's value.
This is the approach I've tried and failed to do it. Maybe it's a stupid mistake or I should change the design at all (would QML help in making this a bit easier?):
#!/usr/bin/env python
import sys
import threading
try:
from PySide import QtGui
from PySide import QtCore
except:
from PyQt4.QtCore import pyqtSlot as Slot
from PyQt4 import QtGui
from PyQt4 import QtCore
class MyUI(QtGui.QWidget):
def __init__(self):
super(MyUI, self).__init__()
self.initUI()
def initUI(self):
someValues = [1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200]
self.setGeometry(100, 300, 640, 450) #window's geometry
lblValueChoice = QtGui.QLabel(self)
lblValueChoice.setGeometry(10, 10, (self.width() - 20), 27)
lblValueChoice.setText("Select your value:")
cmbValueChoice = QtGui.QComboBox(self)
cmbValueChoice.setObjectName("valueChoice")
cmbValueChoice.setGeometry(10, (lblValueChoice.y() + lblValueChoice.height() + 5), (self.width() - 20), 27)
for item in someValues: cmbSerialPorts.addItem(item)
cmbSerialPorts.setCurrentIndex(len(someValues)-1)
pbStartReading = QtGui.QPushButton("Start doing the magic!", self)
pbStartReading.setGeometry(10, (cmbValueChoice.y() + cmbValueChoice.height() + 10), (self.width() - 20), 27)
pbStartReading.setCheckable(True)
pbStartReading.clicked[bool].connect(lambda: self.startReading(bool, str(cmbValueChoice.currentText())))
textEdit = QtGui.QTextEdit(self)
textEdit.setObjectName("textEdit")
textEdit.setGeometry(10, (pbStartReading.y() + pbStartReading.height() + 10), (self.width() - 20), (self.height() - (pbStartReading.y() + pbStartReading.height() + 10) - 10) )
textEdit.append(add_env())
self.setWindowTitle(u'MyMiserableUIFailure')
self.show()
def startReading(self, bool, myvalue):
threading.Thread(target=self.readingLoop, args=(bool, myvalue, )).start()
def readingLoop(self, bool, myvalue):
while bool:
# the error happens in the line below, when I
# try to reference the textEdit control
# -------------------------------------------
textEdit.append("this actually works!\n")
def main():
app = QtGui.QApplication(sys.argv)
theui = MyUI()
sys.exit(app.exec_())
def add_env():
newLine = QtCore.QString("\n")
env_info = "The system is:" + newLine
env_info += newLine + "System/OS name: " + str(platform.system())
env_info += newLine + "System release: " + str(platform.release())
env_info += newLine + "System release version: " + str(platform.version())
env_info += newLine + "Machine type: " + str(platform.machine())
env_info += newLine + "Platform: " + str(platform.platform(aliased=0, terse=1))
env_info += newLine + "Processor: " + str(platform.processor())
env_info += newLine + "Network name: " + str(platform.node())
env_info += newLine + "Python ver(maj,min,patch): " + str(platform.python_version_tuple())
env_info += newLine + "Python build: " + str(platform.python_build())
env_info += newLine + "Python implementation: " + str(platform.python_implementation())
env_info += newLine
env_info += newLine + "***************************"
return env_info
if __name__ == '__main__':
main()

You can't directly reference to ui elements from a different thread. You should use Signals for this. I changed it in your code, see below. I didn't test it, but this is the way this should be done.
#!/usr/bin/env python
import sys
import threading
try:
from PySide import QtGui
from PySide import QtCore
from PySide.QtCore import Signal
except:
from PyQt4.QtCore import pyqtSignal as Signal
from PyQt4 import QtGui
from PyQt4 import QtCore
class MyUI(QtGui.QWidget):
# Add Signal
text_edit_evt = Signal(str)
def __init__(self):
super(MyUI, self).__init__()
self.initUI()
# Connect the signal
self.text_edit_evt.connect(self.textEdit.append)
def initUI(self):
someValues = [1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200]
self.setGeometry(100, 300, 640, 450) #window's geometry
lblValueChoice = QtGui.QLabel(self)
lblValueChoice.setGeometry(10, 10, (self.width() - 20), 27)
lblValueChoice.setText("Select your value:")
cmbValueChoice = QtGui.QComboBox(self)
cmbValueChoice.setObjectName("valueChoice")
cmbValueChoice.setGeometry(10, (lblValueChoice.y() + lblValueChoice.height() + 5), (self.width() - 20), 27)
for item in someValues: cmbSerialPorts.addItem(item)
cmbSerialPorts.setCurrentIndex(len(someValues)-1)
pbStartReading = QtGui.QPushButton("Start doing the magic!", self)
pbStartReading.setGeometry(10, (cmbValueChoice.y() + cmbValueChoice.height() + 10), (self.width() - 20), 27)
pbStartReading.setCheckable(True)
pbStartReading.clicked[bool].connect(lambda: self.startReading(bool, str(cmbValueChoice.currentText())))
# Use self.textEdit so it can be referenced from other functions
self.textEdit = QtGui.QTextEdit(self)
self.textEdit.setObjectName("textEdit")
self.textEdit.setGeometry(10, (pbStartReading.y() + pbStartReading.height() + 10), (self.width() - 20), (self.height() - (pbStartReading.y() + pbStartReading.height() + 10) - 10) )
self.textEdit.append(add_env())
self.setWindowTitle(u'MyMiserableUIFailure')
self.show()
def startReading(self, bool, myvalue):
threading.Thread(target=self.readingLoop, args=(bool, myvalue, )).start()
def readingLoop(self, bool, myvalue):
while bool:
# the error happens in the line below, when I
# try to reference the textEdit control
# -------------------------------------------
# Emit the Signal we created
self.text_edit_evt.emit("this actually works!\n")
def main():
app = QtGui.QApplication(sys.argv)
theui = MyUI()
sys.exit(app.exec_())
def add_env():
newLine = QtCore.QString("\n")
env_info = "The system is:" + newLine
env_info += newLine + "System/OS name: " + str(platform.system())
env_info += newLine + "System release: " + str(platform.release())
env_info += newLine + "System release version: " + str(platform.version())
env_info += newLine + "Machine type: " + str(platform.machine())
env_info += newLine + "Platform: " + str(platform.platform(aliased=0, terse=1))
env_info += newLine + "Processor: " + str(platform.processor())
env_info += newLine + "Network name: " + str(platform.node())
env_info += newLine + "Python ver(maj,min,patch): " + str(platform.python_version_tuple())
env_info += newLine + "Python build: " + str(platform.python_build())
env_info += newLine + "Python implementation: " + str(platform.python_implementation())
env_info += newLine
env_info += newLine + "***************************"
return env_info
if __name__ == '__main__':
main()

Related

pyqt6 change font size on MainWindow resize

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

How to add Scroll bar on the QMainwindow

I display a window where more than 30 Checkbox(on the basic of results in database), This code is static it creates Checkbox but above the window size doesn't show, i want to add scroll to show all Checkbox and select which user want, how can i do that? [It is the second window after we passing and selecting some fields from first window, self.main_query is the query which is selected from first page by user]
import sys
from PyQt5.QtWidgets import QScrollBar, QSlider, QMainWindow, QApplication, QPushButton, QWidget, QAction, QTabWidget, QVBoxLayout, QLabel, QCheckBox
from PyQt5 import QtGui
from PyQt5.QtCore import pyqtSlot
import pymysql
class FormTwo(QWidget):
def __init__(self):
super().__init__()
self.title = 'Second Page which Showing Analytics'
self.title = 'First Main Window'
self.left = 0
self.top = 0
self.width = 700
self.height = 600
self.main_query = " select data from database where "
self.initform2ui()
self.show()
def initform2ui(self):
conn = pymysql.connect(host = 'localhost', user = 'root', password = '********', db = 'db_name')
cur4 = conn.cursor()
query_for_analytics = "select distinct Analytics from analyticsreport"
cur4.execute(query_for_analytics)
self.no_of_analytics = cur4.rowcount
result = cur4.fetchall()
checkbox = 'checkbox3'
r_move = 95
c_move = 75
myFont = QtGui.QFont()
myFont.setBold(True)
self.label2 = QLabel('Analytics', self)
self.label2.setFont(myFont)
self.label2.setStyleSheet('QLabel {Color:blue}')
self.label2.move(100, 50)
self.layout = QVBoxLayout()
#self.layout.addWidget(self.tableWidget)
self.s1 = QSlider()
self.setLayout(self.layout)
self.setWindowTitle('Proceed for the result of Analytics')
self.setGeometry(self.top, self.left, self.width, self.height)
self.button1 = QPushButton('Proceed For Result', self)
self.button1.setStyleSheet('background-color:darkblue; color: white')
self.button1.move(140,300)
self.button1.clicked.connect(self.on_button_pushed)
self.list_of_checkbox_for_analytics = []
for i in range(self.no_of_analytics):
name = str(list(result[i]))
print("name", name)
name = name.replace("[", "")
name = name.replace("]", "")
name = name.replace("'", "")
cb1 = checkbox + str(i)
self.list_of_checkbox_for_analytics.append(name)
self.list_of_checkbox_for_analytics[i] = QCheckBox(name, self)
self.list_of_checkbox_for_analytics[i].adjustSize()
self.list_of_checkbox_for_analytics[i].move(r_move, c_move)
c_move = c_move + 20
def on_button_pushed(self):
initialize_ai = 0
flag = 0
ana_query = ''
for i in range(self.no_of_analytics):
if self.list_of_checkbox_for_analytics[i].isChecked():
print("Checked", self.list_of_checkbox_for_analytics[i].text())
flag = 1
if initialize_ai == 0 and flag == 1:
ana_query = " '" + self.list_of_checkbox_for_analytics[i].text() + "' "
initialize_ai = initialize_ai + 1
flag = 0
if initialize_ai > 0 and flag == 1:
ana_query = ana_query + " or '" + self.list_of_checkbox_for_analytics[i].text() + "' "
flag = 0
if len(ana_query)>2:
ana_query = " and (Analytics = " + ana_query + ")"
main_query = self.main_query + ana_query
else:
main_query = self.main_query
print(main_query)
self.window = QMainWindow()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = FormTwo()
sys.exit(app.exec_())
You have to use a QScrollArea, on the other hand to handle the positions in these cases it is advisable to use layouts.
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
import pymysql
class FormTwo(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.title = 'Second Page which Showing Analytics'
self.left, self.top, self.width, self.height = 0, 0, 700, 600
self.main_query = " select data from database where "
self.initform2ui()
self.show()
def initform2ui(self):
self.setWindowTitle('Proceed for the result of Analytics')
self.setGeometry(self.top, self.left, self.width, self.height)
myFont = QtGui.QFont()
myFont.setBold(True)
self.label2 = QtWidgets.QLabel('Analytics')
self.label2.setFont(myFont)
self.label2.setStyleSheet('QLabel {Color:blue}')
self.button1 = QtWidgets.QPushButton('Proceed For Result')
self.button1.setStyleSheet('background-color:darkblue; color: white')
self.button1.clicked.connect(self.on_button_pushed)
self.list_of_checkbox_for_analytics = []
scrollArea = QtWidgets.QScrollArea()
content_widget = QtWidgets.QWidget()
scrollArea.setWidget(content_widget)
scrollArea.setWidgetResizable(True)
lay = QtWidgets.QVBoxLayout(content_widget)
conn = pymysql.connect(host = 'localhost', user = 'root', password = '********', db = 'db_name')
cur = conn.cursor()
query_for_analytics = "select distinct Analytics from analyticsreport"
cur.execute(query_for_analytics)
for row in cur.fetchall():
name = str(list(row))
name = name.replace("[", "").replace("]", "").replace("'", "")
checkbox = QtWidgets.QCheckBox(name)
checkbox.adjustSize()
lay.addWidget(checkbox)
self.list_of_checkbox_for_analytics.append(checkbox)
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.label2)
layout.addWidget(self.button1)
layout.addWidget(scrollArea)
#QtCore.pyqtSlot()
def on_button_pushed(self):
initialize_ai = 0
flag = False
ana_query = ''
for checkbox in self.list_of_checkbox_for_analytics:
if checkbox.isChecked():
print("Checked", checkbox.text())
flag = True
if initialize_ai == 0 and flag:
ana_query = " '" + checkbox.text() + "' "
initialize_ai += 1
flag = False
if initialize_ai > 0 and flag:
ana_query += " or '" + checkbox.text() + "' "
flag = False
main_query = self.main_query
if len(ana_query) > 2:
ana_query = " and (Analytics = " + ana_query + ")"
main_query += ana_query
print(main_query)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
ex = FormTwo()
sys.exit(app.exec_())

how to use timer in PYQT5 for loop

this is the first writing for asking..
I would like to make a program for currency.
everything works well without looping. I used 'while' but it frozen the GUI.
so I searched for solution, and I found timer in pyqt5. but I don't know how to use. If you can help me, it is really honor to me.
sorry for my bad English.
Here's the my full code
import sys
from PyQt5.QtWidgets import *
from bs4 import BeautifulSoup
import requests
from requests.compat import urljoin
import time
from PyQt5 import QtCore
global Currency
class MyWindow(QWidget):
def __init__(self):
super().__init__()
self.setupUI()
self.Searching_Currency()
def setupUI(self):
self.setGeometry(800, 200, 300, 100)
self.label1 = QLabel("Currency: ")
self.label2 = QLabel("Searching for")
self.label3 = QLabel("")
self.lineEdit2 = QLineEdit()
self.pushButton1= QPushButton("Search")
self.pushButton2= QPushButton("to get alert")
self.pushButton3= QPushButton("reset")
self.pushButton4= QPushButton("quit")
self.pushButton1.clicked.connect(self.btn1_clicked)
self.pushButton2.clicked.connect(self.btn2_clicked)
self.pushButton3.clicked.connect(self.btn3_clicked)
self.pushButton4.clicked.connect(self.btn4_clicked)
layout = QGridLayout()
layout.addWidget(self.label1, 0, 0)
layout.addWidget(self.label3, 0, 1)
layout.addWidget(self.pushButton1, 0, 2)
layout.addWidget(self.label2, 1, 0)
layout.addWidget(self.lineEdit2, 1, 1)
layout.addWidget(self.pushButton2, 1, 2)
layout.addWidget(self.pushButton3, 2, 0)
layout.addWidget(self.pushButton4, 2, 1)
self.setLayout(layout)
def btn1_clicked(self):
global Currency
self.Searching_Currency()
self.label3.setText(str(Currency))
def btn2_clicked(self):
global Currency
textboxValue = float(self.lineEdit2.text())
if textboxValue > Currency:
QMessageBox.question(self, 'alert', "done. it is " + str
(textboxValue), QMessageBox.Ok, QMessageBox.Ok)
# #### I don't know how to use timer.. to check every 1mins.
# self.timer = QtCore.QTimer()
# self.timer.timeout.connect(self.update)
# self.timer.start(5000)
QMessageBox.question(self, 'alert', "test message " + str
(textboxValue), QMessageBox.Ok, QMessageBox.Ok)
#trigger every minute
# while textboxValue < Currency:
# time.sleep(3)
# Currency=Currency-0.10
# break
# QMessageBox.question(self, 'alert', "it is under the " + str(textboxValue), QMessageBox.Ok, QMessageBox.Ok)
def btn3_clicked(self):
self.label3.clear()
def btn4_clicked(self):
sys.exit(0)
def Searching_Currency(self):
base_url = "https://www.finanzen100.de/waehrungen/euro-britisches-pfund-eur-gbp-_H1677059499_11341217/?ac=1"
header = {'User-Agent': 'Mozilla/5.0'}
r = requests.get(base_url,headers=header).text
soup=BeautifulSoup(r,'html.parser')
MyCurrency= soup.select(".quote__price__price")[0]
MyCurrency=MyCurrency.get_text()
MyCurrency =MyCurrency.replace(',','.')
global Currency
Currency = float(MyCurrency)
if __name__ == "__main__":
app = QApplication(sys.argv)
mywindow = MyWindow()
mywindow.show()
app.exec_()
1.this program check currency using Beautiful soup.
2.and compare with the value I put
3.and pop up the message,
The QtCore.QTimer class provides repetitive and single-shot timers.
You wrote everything practical. Add the called slot (showTime).
...
def setupUI(self):
....
self.timer = QtCore.QTimer(self)
self.timer.timeout.connect(self.showTime)
self.timer.start(1000)
...
def showTime(self):
# do something
....
In your example you can use next:
Click "Search"
Click "to get alert"
Look on the process for 1-2 minutes
import sys
import time
from bs4 import BeautifulSoup
import requests
from requests.compat import urljoin
from PyQt5.QtWidgets import *
from PyQt5 import QtCore
from PyQt5 import Qt # +++
global Currency
class MyWindow(QWidget):
def __init__(self):
super().__init__()
self.setupUI()
self.Searching_Currency()
def setupUI(self):
self.setGeometry(800, 200, 350, 170) # -+
self.label1 = QLabel("Currency: ")
self.label2 = QLabel("Searching for")
self.label3 = QLabel("")
self.label4 = QLabel("") # +++
self.lineEdit2 = QLineEdit()
self.pushButton1= QPushButton("Search")
self.pushButton2= QPushButton("to get alert")
self.pushButton3= QPushButton("reset")
self.pushButton4= QPushButton("quit")
self.pushButton1.clicked.connect(self.btn1_clicked)
self.pushButton2.clicked.connect(self.btn2_clicked)
self.pushButton3.clicked.connect(self.btn3_clicked)
self.pushButton4.clicked.connect(self.btn4_clicked)
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
self.lcd = Qt.QLCDNumber() # +++
self.lcd.setDigitCount(7)
self.lcdTime = Qt.QLCDNumber() #self
self.lcdTime.setSegmentStyle(Qt.QLCDNumber.Filled)
self.lcdTime.setDigitCount(8)
self.timer1 = Qt.QTimer(self)
self.timer1.timeout.connect(self.showTime)
self.timer1.start(1000)
layout = QGridLayout()
layout.addWidget(self.lcdTime, 0, 0, 1, 3) # +++
layout.addWidget(self.label1, 1, 0)
layout.addWidget(self.label3, 1, 1)
layout.addWidget(self.pushButton1, 1, 2)
layout.addWidget(self.label2, 2, 0)
layout.addWidget(self.lineEdit2, 2, 1)
layout.addWidget(self.pushButton2, 2, 2)
layout.addWidget(self.pushButton3, 3, 0)
layout.addWidget(self.pushButton4, 3, 1)
layout.addWidget(self.label4, 3, 2) # +++
layout.addWidget(self.lcd, 4, 0, 1, 3) # +++
self.setLayout(layout)
self.timer = QtCore.QTimer() # +++
self.timer.timeout.connect(self.show_textboxValue) # +++
def btn1_clicked(self):
global Currency
self.Searching_Currency()
self.label3.setText(str(Currency))
def btn2_clicked(self):
global Currency
try: # +++
self.textboxValue = float(self.lineEdit2.text())
except:
self.textboxValue = Currency
self.label4.setText(str(Currency))
##if self.textboxValue > Currency:
## QMessageBox.question(self, 'alert', "done. it is " + str
## (self.textboxValue), QMessageBox.Ok, QMessageBox.Ok)
# #### I don't know how to use timer.. to check every 1mins.
# self.timer = QtCore.QTimer()
# self.timer.timeout.connect(self.update)
self.num = 0 # +++
self.timer.start(1000) # +++
##QMessageBox.question(self, 'alert', "test message " + str
## (self.textboxValue), QMessageBox.Ok, QMessageBox.Ok)
#trigger every minute
# while self.textboxValue < Currency:
# time.sleep(3)
# Currency=Currency-0.10
# break
# QMessageBox.question(self, 'alert', "it is under the " + str(self.textboxValue), QMessageBox.Ok, QMessageBox.Ok)
def show_textboxValue(self):
global Currency
self.num += 1
self.lcd.display(str(self.num))
if self.textboxValue < Currency:
#Currency = round(Currency - 0.10, 4)
QMessageBox.information(self, "QMessageBox.information",
"textboxValue`{}` < Currency`{}`".format(str(self.textboxValue), str(Currency)))
elif self.textboxValue > Currency:
self.label4.setText(str(Currency))
QMessageBox.warning(self, "QMessageBox.warning!",
"textboxValue`{}` < Currency`{}`".format(str(self.textboxValue), str(Currency)))
else:
pass
self.textboxValue = Currency #float(self.label4.text())
if not self.num % 30:
self.Searching_Currency()
def btn3_clicked(self):
self.label3.clear()
def btn4_clicked(self):
sys.exit(0)
def Searching_Currency(self):
base_url = "https://www.finanzen100.de/waehrungen/euro-britisches-pfund-eur-gbp-_H1677059499_11341217/?ac=1"
header = {'User-Agent': 'Mozilla/5.0'}
r = requests.get(base_url,headers=header).text
soup = BeautifulSoup(r,'html.parser')
MyCurrency = soup.select(".quote__price__price")[0]
MyCurrency = MyCurrency.get_text()
MyCurrency = MyCurrency.replace(',','.')
global Currency
Currency = float(MyCurrency)
def showTime(self):
time = Qt.QTime.currentTime()
text = time.toString("hh:mm:ss")
if ((time.second() % 2) == 0):
text = text[0:2] + ' ' + text[3:5] + ' ' + text[6:]
self.lcdTime.display(text)
if __name__ == "__main__":
app = QApplication(sys.argv)
mywindow = MyWindow()
mywindow.show()
app.exec_()

Showing Consecutive images on a QLabel PyQt4

I'm trying to show consecutive images on a QLabel
the images are numbered from 0000000 to 0000199
the problem is that the num variable prints empty string
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys, time
class Animation(QMainWindow):
def __init__(self, parent=None):
super(Animation, self).__init__(parent)
self.resize(QSize(720, 480))
self.imageViewer = QLabel(self)
self.setCentralWidget(self.imageViewer)
startBtn = QPushButton("start", self)
startBtn.clicked.connect(self.start)
self.statusBar().addWidget(startBtn)
def start(self):
i = 0
while 1:
num = ("0" * (len(str(i)) - 7)) + str(i)
name = "frame" + num + ".png"
print ("0" * (len(str(i)) - 7))
self.imageViewer.setPixmap(QPixmap(name))
if i == 199:
break
i += 1
time.sleep(1)
app = QApplication(sys.argv)
test = Animation()
test.show()
app.exec_()
Please help
len(str(i)) - 7 returns a negative number. You need to swap it around:
num = '0' * (7-len(str(i))) + str(i)

Add more than one line to a QTextEdit PyQt

I am experiencing a rather strange issue with my PyQT QTextEdit.
When I enter a string from my QLineEdit it adds it but say I enter another the first string disappears I assume that's because I am not appending the text.
Any idea how I can do this?
Here is the relevant code:
self.mytext.setText(str(self.user) + ": " + str(self.line.text()) + "\n")
and the important one
self.mySignal.emit(self.decrypt_my_message(str(msg)).strip() + "\n")
Edit
I figured it out I needed to use a QTextCursor
self.cursor = QTextCursor(self.mytext.document())
self.cursor.insertText(str(self.user) + ": " + str(self.line.text()) + "\n")
The setText() method replaces all the current text, so you just need to use the append() method instead. (Note that both these methods automatically add a trailing newline).
import sys
from PyQt4 import QtGui
class Window(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
layout = QtGui.QVBoxLayout(self)
self.button = QtGui.QPushButton('Test')
self.edit = QtGui.QTextEdit()
layout.addWidget(self.edit)
layout.addWidget(self.button)
self.button.clicked.connect(self.handleTest)
def handleTest(self):
self.edit.append('spam: spam spam spam spam')
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
win = Window()
win.show()
sys.exit(app.exec_())

Categories