pyqt6 change font size on MainWindow resize - python

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

Related

Destroy all Child Window

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()

How to set my data into QscrollArea using pyqt4

Here in my sample code i want to display my dictionary data into scroll Area.I tried so many ways but i am not getting properly.i did n't get any error also.Can any one please tell me why my data is not displayed in scroll area.where i did the mistake in below program please guide me.Thank you in advance.
Given below is my sample code:
import sys
from PyQt4 import QtGui, QtCore
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
self.products_list = {
"Givers":{
"price": 140,
"Quantity": 100,
"Discount": 0,
"Total_price":14000,
"Paid_amount":14000},
"New_Member":{
"price": 1200,
"Quantity": 10,
"Discount": 0,
"Total_price":12000,
"Paid_amount":12000},
"YearMembers_Ribbons":{
"price": 110,
"Quantity": 0,
"Discount": 0,
"Total_price":1100,
"Paid_amount":1100}
}
self.grid = QtGui.QGridLayout(self)
hbox = QtGui.QHBoxLayout()
self.clbtn = QtGui.QPushButton('close')
self.clbtn.clicked.connect(self.close)
self.lab = QtGui.QLabel("orders")
hbox.addWidget(self.lab,alignment = QtCore.Qt.AlignCenter)
hbox.addStretch()
hbox.addWidget(self.clbtn,alignment = QtCore.Qt.AlignRight)
self.grid.addLayout(hbox,0,0)
self.line = QtGui.QFrame(frameShape=QtGui.QFrame.HLine)
self.grid.addWidget(self.line,1,0)
self.main_hbox = QtGui.QHBoxLayout()
self.scroll = QtGui.QScrollArea()
self.show()
self.VBox = QtGui.QVBoxLayout()
self.Date = QtGui.QLabel("25-2-2018",objectName="small",alignment = QtCore.Qt.AlignRight)
self.v_city = QtGui.QLabel("bangalore",alignment = QtCore.Qt.AlignCenter)
self.v_state = QtGui.QLabel("karnataka",alignment = QtCore.Qt.AlignCenter)
self.v_pincode = QtGui.QLabel("560003",alignment = QtCore.Qt.AlignCenter)
self.v_country = QtGui.QLabel("India",alignment = QtCore.Qt.AlignCenter)
self.VBox.addWidget(self.Date)
self.VBox.addWidget(self.v_city)
self.VBox.addWidget(self.v_state)
self.VBox.addWidget(self.v_pincode)
self.VBox.addWidget(self.v_country)
self.main_hbox.addLayout(self.VBox)
self.main_hbox.addWidget(self.scroll)
self.grid.addLayout(self.main_hbox,2,0)
w2 = QtGui.QWidget()
self.scroll.setWidget(w2)
grid1 = QtGui.QGridLayout(w2)
self.items_Vboxlay = QtGui.QVBoxLayout()
self.vbox2 = QtGui.QVBoxLayout()
for key, value in self.products_list.items():
keys = [ vk for vk in value.keys()]
values = [ vv for vv in value.values()]
self.item_label = QtGui.QLabel(str(key), objectName="small")
self.vbox2.addWidget(self.item_label)
self.hbox1 = QtGui.QHBoxLayout()
self.hbox2 = QtGui.QHBoxLayout()
self.price = QtGui.QLabel(keys[1] + ": " + u'\u20B9 ' +str(values[1]))
self.qnty = QtGui.QLabel(keys[3] + ": " + str(values[3]))
self.discount = QtGui.QLabel(keys[0] + ": " + u'\u20B9 ' + str(values[0]))
self.totalprice = QtGui.QLabel(keys[2] + ": " + u'\u20B9 ' + str(values[2]))
self.status = QtGui.QLabel("Status" + ": "+ "Created")
self.ref_amount = QtGui.QLabel("Refund Amount"+": "+ "0")
self.ref_status = QtGui.QLabel("Refund Status"+": "+ "False")
self.hbox1.addWidget(self.price)
self.hbox1.addWidget(self.qnty)
self.hbox1.addWidget(self.discount)
self.hbox1.addWidget(self.totalprice)
self.hbox2.addWidget(self.status)
self.hbox2.addWidget(self.ref_amount)
self.hbox2.addWidget(self.ref_status)
self.line4 = QtGui.QFrame()
self.line4.setFrameShape(QtGui.QFrame.HLine)
self.vbox2.addLayout(self.hbox1)
self.vbox2.addLayout(self.hbox2)
self.vbox2.addWidget(self.line4)
self.items_Vboxlay.addLayout(self.vbox2)
grid1.addLayout(self.items_Vboxlay,0,0)
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
ex.show()
ex.resize(500,300)
sys.exit(app.exec_())
if __name__ == '__main__':
main()
When a widget is set in a ScrollArea the size it uses is that of the widget at that moment, in your case it does not have any size so the widget will have size 0, 0 and although you add child widgets through a QScrollArea layout, it does not will take into account, so for QScrollArea to monitor the size you must enable the widgetResizable property:
self.scroll = QtGui.QScrollArea(widgetResizable=True)

Restrict a Qdockwidget to a quadrant rather than Left/Right/Top/Bottom

I have three main sections of a main window, where the left side (critical data) should take the entire height of the window, while the data on the right should be split between top and bottom. Data in the lower right is related, but not critical - which is why I'd like it to be un-dockable/closable.
The Qt documentation shows an example of this in C++, but I have no idea how to turn this into Python code, as I have no C++ experience.
The Qt Designer application limits the user to Left/Right/Top/Bottom, and limiting the maximum width of the widget doesn't allow me to occupy the un-used space (i.e. doesn't allow the list widget on the left to take up the full height of the main window)
Long story short, to get a Qdockwidget into the lower right corner, you have to put another dock widget above it (it's still limited to Right/Left/Top/Bottom DockWidgetArea). After looking at the answer from eyllanesc below, I'll post two solutions. First, a simplified version of his code and then a modified version of the code I originally posted.
Eyllanesc's translation from the C++ example from I mentioned above:
from PyQt4 import QtCore, QtGui
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.resize(600, 600)
self.centralWidget = QtGui.QTextEdit()
self.setCentralWidget(self.centralWidget)
# Upper table widget
dock = QtGui.QDockWidget("Upper", self.centralWidget)
dock.setAllowedAreas(QtCore.Qt.RightDockWidgetArea)
self.tableWidget = QtGui.QTableWidget(dock)
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.setColumnCount(6)
self.tableWidget.setRowCount(7)
for i in range(7):
item = QtGui.QTableWidgetItem()
self.tableWidget.setVerticalHeaderItem(i, item)
self.tableWidget.verticalHeaderItem(i).setText("Item " + str(i + 1))
for i in range(6):
item = QtGui.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(i, item)
dock.setWidget(self.tableWidget)
self.addDockWidget(QtCore.Qt.RightDockWidgetArea, dock)
# Lower table widget
dock = QtGui.QDockWidget("Lower", self.centralWidget)
self.tableWidget_2 = QtGui.QTableWidget(dock)
self.tableWidget_2.setObjectName("tableWidget_2")
self.tableWidget_2.setColumnCount(6)
self.tableWidget_2.setRowCount(7)
for i in range(7):
item = QtGui.QTableWidgetItem()
self.tableWidget_2.setVerticalHeaderItem(i, item)
for i in range(6):
item = QtGui.QTableWidgetItem()
self.tableWidget_2.setHorizontalHeaderItem(i, item)
dock.setWidget(self.tableWidget_2);
self.addDockWidget(QtCore.Qt.RightDockWidgetArea, dock)
self.listWidget = QtGui.QListWidget(self.centralWidget)
self.listWidget.setLayoutDirection(QtCore.Qt.RightToLeft)
self.listWidget.setObjectName("listWidget")
for i in range(10):
item = QtGui.QListWidgetItem()
self.listWidget.addItem(item)
item = self.listWidget.item(i)
item.setText("Item " + str(i + 1))
self.listWidget.setMinimumSize(QtCore.QSize(340, 600))
self.setWindowTitle("Dock Widgets")
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
And the modified version of the code I originally used:
from PyQt4 import QtCore, QtGui
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.gridLayout = QtGui.QGridLayout(self.centralwidget)
self.gridLayout.setObjectName("gridLayout")
self.listWidget = QtGui.QListWidget(self.centralwidget)
self.listWidget.setObjectName("listWidget")
self.gridLayout.addWidget(self.listWidget, 0, 0, 1, 1)
self.listWidget.setLayoutDirection(QtCore.Qt.RightToLeft)
for i in range(10):
item = QtGui.QListWidgetItem()
self.listWidget.addItem(item)
item = self.listWidget.item(i)
item.setText("Item " + str(i + 1))
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 26))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.dockWidget = QtGui.QDockWidget(MainWindow)
self.dockWidget.setFeatures(QtGui.QDockWidget.DockWidgetFloatable)
self.dockWidget.setObjectName("dockWidget")
self.dockWidgetContents = QtGui.QWidget()
self.dockWidgetContents.setObjectName("dockWidgetContents")
self.tableWidget = QtGui.QTableWidget(self.dockWidgetContents)
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.setColumnCount(6)
self.tableWidget.setRowCount(7)
for i in range(7):
item = QtGui.QTableWidgetItem()
self.tableWidget.setVerticalHeaderItem(i, item)
self.tableWidget.verticalHeaderItem(i).setText("Item " + str(i + 1))
for i in range(6):
item = QtGui.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(i, item)
self.gridLayout_2 = QtGui.QGridLayout(self.dockWidgetContents)
self.gridLayout_2.setObjectName("gridLayout_2")
self.gridLayout_2.addWidget(self.tableWidget, 0, 0, 1, 1)
self.dockWidget.setWidget(self.dockWidgetContents)
MainWindow.addDockWidget(QtCore.Qt.DockWidgetArea(2), self.dockWidget)
self.dockWidget_2 = QtGui.QDockWidget(MainWindow)
self.dockWidget_2.setFeatures(QtGui.QDockWidget.DockWidgetClosable|QtGui.QDockWidget.DockWidgetFloatable)
self.dockWidget_2.setObjectName("dockWidget_2")
self.dockWidgetContents_2 = QtGui.QWidget()
self.dockWidgetContents_2.setObjectName("dockWidgetContents_2")
self.gridLayout_3 = QtGui.QGridLayout(self.dockWidgetContents_2)
self.gridLayout_3.setObjectName("gridLayout_3")
self.tableWidget_2 = QtGui.QTableWidget(self.dockWidgetContents)
self.tableWidget_2.setObjectName("tableWidget_2")
self.tableWidget_2.setColumnCount(6)
self.tableWidget_2.setRowCount(7)
for i in range(7):
item = QtGui.QTableWidgetItem()
self.tableWidget_2.setVerticalHeaderItem(i, item)
for i in range(6):
item = QtGui.QTableWidgetItem()
self.tableWidget_2.setHorizontalHeaderItem(i, item)
self.gridLayout_3.addWidget(self.tableWidget_2, 0, 0, 1, 1)
self.dockWidget_2.setWidget(self.dockWidgetContents_2)
MainWindow.addDockWidget(QtCore.Qt.DockWidgetArea(2), self.dockWidget_2)
MainWindow.setWindowTitle("MainWindow")
QtCore.QMetaObject.connectSlotsByName(MainWindow)
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_())## Heading ##
My answer is a translation of this example: http://doc.qt.io/qt-5/qtwidgets-mainwindows-dockwidgets-example.html, so future readers can use it to make a translation from the C++ code to Python.
from PyQt4 import QtCore, QtGui
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.textEdit = QtGui.QTextEdit()
self.setCentralWidget(self.textEdit)
self.createActions()
self.createStatusBar()
self.createDockWindows()
self.setWindowTitle("Dock Widgets")
self.newLetter()
self.setUnifiedTitleAndToolBarOnMac(True)
def newLetter(self):
self.textEdit.clear()
cursor = QtGui.QTextCursor(self.textEdit.textCursor())
cursor.movePosition(QtGui.QTextCursor.Start)
topFrame = cursor.currentFrame()
topFrameFormat = topFrame.frameFormat()
topFrameFormat.setPadding(16)
topFrame.setFrameFormat(topFrameFormat)
textFormat = QtGui.QTextCharFormat()
boldFormat = QtGui.QTextCharFormat()
boldFormat.setFontWeight(QtGui.QFont.Bold)
italicFormat = QtGui.QTextCharFormat()
italicFormat.setFontItalic(True)
tableFormat = QtGui.QTextTableFormat()
tableFormat.setBorder(1)
tableFormat.setCellPadding(16)
tableFormat.setAlignment(QtCore.Qt.AlignRight)
cursor.insertTable(1, 1, tableFormat)
cursor.insertText("The Firm", boldFormat)
cursor.insertBlock()
cursor.insertText("321 City Street", textFormat)
cursor.insertBlock()
cursor.insertText("Industry Park")
cursor.insertBlock()
cursor.insertText("Some Country")
cursor.setPosition(topFrame.lastPosition())
cursor.insertText(QtCore.QDate.currentDate().toString("d MMMM yyyy"), textFormat)
cursor.insertBlock()
cursor.insertBlock()
cursor.insertText("Dear ", textFormat)
cursor.insertText("NAME", italicFormat)
cursor.insertText(",", textFormat)
for i in range(3):
cursor.insertBlock()
cursor.insertText("Yours sincerely,", textFormat)
for i in range(3):
cursor.insertBlock()
cursor.insertText("The Boss", textFormat)
cursor.insertBlock()
cursor.insertText("ADDRESS", italicFormat)
def print_(self):
document = self.textEdit.document()
printer = QtGui.QPrinter()
dlg = QtGui.QPrintDialog(printer, self)
if dlg.exec() != QtGui.QDialog.Accepted:
return
document.print_(printer)
self.statusBar().showMessage("Ready", 2000)
def save(self):
fileName = QtGui.QFileDialog.getSaveFileName(self,
"Choose a file name", ".", "HTML document (*.html *.htm)")
if not fileName:
return
file = QtCore.QFile(fileName)
if not file.open(QtCore.QFile.WriteOnly | QtCore.QFile.Text):
QtGui.QMessageBox.warning(self, "Dock Widgets",
"Cannot write file {}:\n{}."
.format(QtCore.QDir.toNativeSeparators(fileName), file.errorString()))
return
out = QTextStream(file)
QtGui.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
out << textEdit.toHtml()
QtGui.QApplication.restoreOverrideCursor()
self.statusBar().showMessage("Saved '{}'".format(fileName), 2000)
def undo(self):
document = self.textEdit.document()
document.undo()
def insertCustomer(self, customer):
if not customer:
return
customerList = customer.split(", ")
document = self.textEdit.document()
cursor = document.find("NAME")
if not cursor.isNull():
cursor.beginEditBlock()
cursor.insertText(customerList[0])
oldcursor = cursor
cursor = document.find("ADDRESS")
if not cursor.isNull():
for c in customerList:
cursor.insertBlock()
cursor.insertText(c)
cursor.endEditBlock()
else:
oldcursor.endEditBlock()
def addParagraph(self, paragraph):
if not paragraph:
return
document = self.textEdit.document()
cursor = document.find("Yours sincerely,")
if cursor.isNull():
return
cursor.beginEditBlock()
cursor.movePosition(QtGui.QTextCursor.PreviousBlock, QtGui.QTextCursor.MoveAnchor, 2)
cursor.insertBlock()
cursor.insertText(paragraph)
cursor.insertBlock()
cursor.endEditBlock()
def about(self):
QtGui.QMessageBox.about(self, "About Dock Widgets",
"The <b>Dock Widgets</b> example demonstrates how to "
"use Qt's dock widgets. You can enter your own text, "
"click a customer to add a customer name and "
"address, and click standard paragraphs to add them.")
def createActions(self):
fileMenu = self.menuBar().addMenu("&File")
fileToolBar = self.addToolBar("File")
newIcon = QtGui.QIcon.fromTheme("document-new", QtGui.QIcon(":/images/new.png"))
newLetterAct = QtGui.QAction(newIcon, "&New Letter", self)
newLetterAct.setShortcuts(QtGui.QKeySequence.New)
newLetterAct.setStatusTip("Create a new form letter")
newLetterAct.triggered.connect(self.newLetter)
fileMenu.addAction(newLetterAct)
fileToolBar.addAction(newLetterAct)
saveIcon = QtGui.QIcon.fromTheme("document-save", QtGui.QIcon(":/images/save.png"))
saveAct = QtGui.QAction(saveIcon, "&Save...", self)
saveAct.setShortcuts(QtGui.QKeySequence.Save)
saveAct.setStatusTip("Save the current form letter")
saveAct.triggered.connect(self.save)
fileMenu.addAction(saveAct)
fileToolBar.addAction(saveAct)
printIcon = QtGui.QIcon.fromTheme("document-print", QtGui.QIcon(":/images/print.png"))
printAct = QtGui.QAction(printIcon,"&Print...", self)
printAct.setShortcuts(QtGui.QKeySequence.Print)
printAct.setStatusTip("Print the current form letter")
printAct.triggered.connect(self.print_)
fileMenu.addAction(printAct)
fileToolBar.addAction(printAct)
fileMenu.addSeparator()
quitAct = fileMenu.addAction("&Quit", self.close)
quitAct.setShortcuts(QtGui.QKeySequence.Quit)
quitAct.setStatusTip("Quit the application")
editMenu = self.menuBar().addMenu("&Edit")
editToolBar = self.addToolBar("Edit")
undoIcon = QtGui.QIcon.fromTheme("edit-undo", QtGui.QIcon(":/images/undo.png"))
undoAct = QtGui.QAction(undoIcon, "&Undo", self)
undoAct.setShortcuts(QtGui.QKeySequence.Undo)
undoAct.setStatusTip("Undo the last editing action")
undoAct.triggered.connect(self.undo)
editMenu.addAction(undoAct)
editToolBar.addAction(undoAct)
self.viewMenu = self.menuBar().addMenu("&View")
self.menuBar().addSeparator()
helpMenu = self.menuBar().addMenu("&Help")
aboutAct = helpMenu.addAction("&About", self.about)
aboutAct.setStatusTip("Show the application's About box")
aboutQtAct = helpMenu.addAction("About &Qt", QtGui.qApp.aboutQt)
aboutQtAct.setStatusTip("Show the Qt library's About box")
def createStatusBar(self):
self.statusBar().showMessage("Ready")
def createDockWindows(self):
dock = QtGui.QDockWidget("Customers", self)
dock.setAllowedAreas(QtCore.Qt.LeftDockWidgetArea | QtCore.Qt.RightDockWidgetArea)
self.customerList = QtGui.QListWidget(dock)
self.customerList.addItems([
"John Doe, Harmony Enterprises, 12 Lakeside, Ambleton",
"Jane Doe, Memorabilia, 23 Watersedge, Beaton",
"Tammy Shea, Tiblanka, 38 Sea Views, Carlton",
"Tim Sheen, Caraba Gifts, 48 Ocean Way, Deal",
"Sol Harvey, Chicos Coffee, 53 New Springs, Eccleston",
"Sally Hobart, Tiroli Tea, 67 Long River, Fedula"])
dock.setWidget(self.customerList)
self.addDockWidget(QtCore.Qt.RightDockWidgetArea, dock)
self.viewMenu.addAction(dock.toggleViewAction())
dock = QtGui.QDockWidget("Paragraphs", self)
self.paragraphsList = QtGui.QListWidget(dock)
self.paragraphsList.addItems([
"""Thank you for your payment which we have received today.""",
"""Your order has been dispatched and should be with you \
within 28 days.""",
"""We have dispatched those items that were in stock. The \
rest of your order will be dispatched once all the \
remaining items have arrived at our warehouse. No \
additional shipping charges will be made.""",
"""You made a small overpayment (less than $5) which we \
will keep on account for you, or return at your request.""",
"""You made a small underpayment (less than $1), but we have \
sent your order anyway. We'll add this underpayment to \
your next bill.""",
"""Unfortunately you did not send enough money. Please remit \
an additional $. Your order will be dispatched as soon as \
the complete amount has been received.""",
"""You made an overpayment (more than $5). Do you wish to \
buy more items, or should we return the excess to you?"""])
dock.setWidget(self.paragraphsList);
self.addDockWidget(QtCore.Qt.RightDockWidgetArea, dock)
self.viewMenu.addAction(dock.toggleViewAction())
self.customerList.currentTextChanged.connect(self.insertCustomer)
self.paragraphsList.currentTextChanged.connect(self.addParagraph)
# import dockwidgets_rc
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
The complete example can be found at the following link. The .qrc file has been compiled for Python 2 (dockwidgets_rc.py), but for Python 3 you must recompile the file.

Python QT - Refresh all widgets

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_())

How to reference PyQt UI elements from around the code?

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()

Categories