pyqt5 button click event works in debug but not when runing - python

i have a main code that runs a main UI window, from the main UI window im passing to other window, i tried to implement a back button but for some reason it works only when im in debug mode.
main UI window:
from PyQt5 import QtCore, QtGui, QtWidgets
import UI.plantManagment as plantManagment
class Ui_MainWindow(object):
def __init__(self,MainWindow,loadedgreenhouses) -> None:
self.MainWindow=MainWindow
self.loadedgreenhouses=loadedgreenhouses
def setupUi(self):
self.MainWindow.setObjectName("MainWindow")
self.MainWindow.resize(480, 480)
self.MainWindow.setMinimumSize(QtCore.QSize(480, 480))
self.MainWindow.setMaximumSize(QtCore.QSize(480, 480))
self.MainWindow.setTabletTracking(False)
self.MainWindow.setContextMenuPolicy(QtCore.Qt.NoContextMenu)
self.MainWindow.setAnimated(True)
self.MainWindow.setDocumentMode(False)
self.MainWindow.setTabShape(QtWidgets.QTabWidget.Rounded)
self.centralwidget = QtWidgets.QWidget(self.MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(70, 70, 321, 361))
self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
self.verticalLayout.setContentsMargins(0, 0, 0, 0)
self.verticalLayout.setObjectName("verticalLayout")
spacerItem = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.verticalLayout.addItem(spacerItem)
self.btn_managePlants = QtWidgets.QPushButton(self.verticalLayoutWidget)
self.btn_managePlants.setMinimumSize(QtCore.QSize(0, 80))
font = QtGui.QFont()
font.setPointSize(24)
self.btn_managePlants.setFont(font)
self.btn_managePlants.setObjectName("btn_managePlants")
self.verticalLayout.addWidget(self.btn_managePlants)
self.btn_managePlants.clicked.connect(self.loadPalntsUI)
spacerItem1 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.verticalLayout.addItem(spacerItem1)
self.btn_manageGreenHouses = QtWidgets.QPushButton(self.verticalLayoutWidget)
self.btn_manageGreenHouses.setMinimumSize(QtCore.QSize(0, 80))
font = QtGui.QFont()
font.setPointSize(24)
self.btn_manageGreenHouses.setFont(font)
self.btn_manageGreenHouses.setObjectName("btn_manageGreenHouses")
self.verticalLayout.addWidget(self.btn_manageGreenHouses)
spacerItem2 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.verticalLayout.addItem(spacerItem2)
self.btn_harvestAll = QtWidgets.QPushButton(self.verticalLayoutWidget)
self.btn_harvestAll.setMinimumSize(QtCore.QSize(0, 80))
font = QtGui.QFont()
font.setPointSize(24)
self.btn_harvestAll.setFont(font)
self.btn_harvestAll.setCheckable(False)
self.btn_harvestAll.setChecked(False)
self.btn_harvestAll.setObjectName("btn_harvestAll")
self.verticalLayout.addWidget(self.btn_harvestAll)
spacerItem3 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.verticalLayout.addItem(spacerItem3)
self.lable_harvestableNum = QtWidgets.QLabel(self.centralwidget)
self.lable_harvestableNum.setGeometry(QtCore.QRect(70, 20, 321, 41))
font = QtGui.QFont()
font.setPointSize(18)
font.setBold(False)
font.setWeight(50)
font.setStrikeOut(False)
font.setKerning(False)
self.lable_harvestableNum.setFont(font)
self.lable_harvestableNum.setLayoutDirection(QtCore.Qt.LeftToRight)
self.lable_harvestableNum.setScaledContents(False)
self.lable_harvestableNum.setAlignment(QtCore.Qt.AlignCenter)
self.lable_harvestableNum.setWordWrap(False)
self.lable_harvestableNum.setIndent(2)
self.lable_harvestableNum.setTextInteractionFlags(QtCore.Qt.LinksAccessibleByMouse)
self.lable_harvestableNum.setObjectName("lable_harvestableNum")
self.MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(self.MainWindow)
self.statusbar.setObjectName("statusbar")
self.MainWindow.setStatusBar(self.statusbar)
self.retranslateUi()
QtCore.QMetaObject.connectSlotsByName(self.MainWindow)
def retranslateUi(self):
_translate = QtCore.QCoreApplication.translate
self.MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.btn_managePlants.setText(_translate("MainWindow", "manage plants"))
self.btn_manageGreenHouses.setText(_translate("MainWindow", "manage greenhouses"))
self.btn_harvestAll.setText(_translate("MainWindow", "harvest all"))
self.lable_harvestableNum.setText(_translate("MainWindow", f"plant ready for harvest: {self.calcRadyToHarvest()}"))
def calcRadyToHarvest(self):
cnt=0
for gh in self.loadedgreenhouses:
for pp in gh.palntingPoints:
if pp.harvestPlant():
cnt+=1
return cnt
def loadPalntsUI(self):
ui = plantManagment.Ui_MainWindow(self.MainWindow,self.loadedgreenhouses)
ui.setupUi()
ui.MainWindow.show()
here the event is working as intended when i click on self.btn_managePlants.clicked.connect(self.loadPalntsUI) and it loads me the next window witouth a problem.
the second window (where the button doesn't work):
from time import sleep
from PyQt5 import QtCore, QtGui, QtWidgets
import Plant
import UI.mainWindow as mainWindow
class Ui_MainWindow(object):
def __init__(self,MainWindow,loadedgreenhouses) -> None:
self.MainWindow=MainWindow
self.loadedgreenhouses=loadedgreenhouses
def setupUi(self):
self.MainWindow.setObjectName("MainWindow")
self.MainWindow.setWindowModality(QtCore.Qt.NonModal)
self.MainWindow.setEnabled(True)
self.MainWindow.resize(627, 409)
self.MainWindow.setMinimumSize(QtCore.QSize(627, 409))
self.MainWindow.setMaximumSize(QtCore.QSize(627, 409))
self.MainWindow.setTabShape(QtWidgets.QTabWidget.Rounded)
self.centralwidget = QtWidgets.QWidget(self.MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(20, 20, 591, 361))
self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
self.verticalLayout.setContentsMargins(0, 0, 0, 0)
self.verticalLayout.setObjectName("verticalLayout")
self.label_plants = QtWidgets.QLabel(self.verticalLayoutWidget)
font = QtGui.QFont()
font.setPointSize(18)
self.label_plants.setFont(font)
self.label_plants.setObjectName("label_plants")
self.verticalLayout.addWidget(self.label_plants)
self.tableWidget = QtWidgets.QTableWidget(self.verticalLayoutWidget)
self.tableWidget.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)
self.tableWidget.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.setColumnCount(4)
self.tableWidget.setRowCount(0)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(0, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(1, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(2, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(3, item)
self.tableWidget.horizontalHeader().setStretchLastSection(True)
self.tableWidget.verticalHeader().setVisible(False)
self.tableWidget.verticalHeader().setHighlightSections(False)
self.verticalLayout.addWidget(self.tableWidget)
self.tableWidget.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers) #forbid editing
self.tableWidget.setRowCount(len(Plant.Plant.kindsList)) #len of number of plants
for i,p in enumerate(Plant.Plant.plantsLst): #add to the table
self.tableWidget.setItem(i, 0, QtWidgets.QTableWidgetItem(p.kind))
self.tableWidget.setItem(i, 1, QtWidgets.QTableWidgetItem(str(p.grow_time)))
self.tableWidget.setItem(i, 2, QtWidgets.QTableWidgetItem(str(p.temp_min)))
self.tableWidget.setItem(i, 3, QtWidgets.QTableWidgetItem(str(p.temp_max)))
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
self.btn_back = QtWidgets.QPushButton(self.verticalLayoutWidget)
font = QtGui.QFont()
font.setPointSize(20)
self.btn_back.setFont(font)
self.btn_back.setObjectName("btn_back")
self.horizontalLayout.addWidget(self.btn_back)
self.btn_back.clicked.connect(self.backBtn)
self.btn_delete = QtWidgets.QPushButton(self.verticalLayoutWidget)
font = QtGui.QFont()
font.setPointSize(20)
self.btn_delete.setFont(font)
self.btn_delete.setObjectName("btn_delete")
self.horizontalLayout.addWidget(self.btn_delete)
self.btn_addPlant = QtWidgets.QPushButton(self.verticalLayoutWidget)
font = QtGui.QFont()
font.setPointSize(20)
self.btn_addPlant.setFont(font)
self.btn_addPlant.setObjectName("btn_addPlant")
self.horizontalLayout.addWidget(self.btn_addPlant)
self.verticalLayout.addLayout(self.horizontalLayout)
self.MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(self.MainWindow)
self.statusbar.setObjectName("statusbar")
self.MainWindow.setStatusBar(self.statusbar)
self.retranslateUi()
QtCore.QMetaObject.connectSlotsByName(self.MainWindow)
def retranslateUi(self):
_translate = QtCore.QCoreApplication.translate
self.MainWindow.setWindowTitle(_translate("MainWindow", "plant managment"))
self.label_plants.setText(_translate("MainWindow", "plants:"))
item = self.tableWidget.horizontalHeaderItem(0)
item.setText(_translate("MainWindow", "kind"))
item = self.tableWidget.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", "grow time"))
item = self.tableWidget.horizontalHeaderItem(2)
item.setText(_translate("MainWindow", "min temperature"))
item = self.tableWidget.horizontalHeaderItem(3)
item.setText(_translate("MainWindow", "max temperature"))
self.btn_back.setText(_translate("MainWindow", "back"))
self.btn_delete.setText(_translate("MainWindow", "delete"))
self.btn_addPlant.setText(_translate("MainWindow", "add plant"))
self.tableWidget.show()
def backBtn(self):
print("the lalala")
ui = mainWindow.Ui_MainWindow(self.MainWindow,self.loadedgreenhouses)
ui.setupUi()
self.MainWindow.show()
the event should be triggered by self.btn_back.clicked.connect(self.backBtn) but as i said it would work only in debug mode.
i tried to self.btn_back.clicked.connect(lambda : self.backBtn()) which did took me back to the main UI window but then none of the buttons in that window worked :|

Related

Qt5 QComboBox focusOutEvent

I have built a GUI and among other things I am using a QComboBox (drop-down menu) with three entries. I want to enable/disable some other boxes and labels in the GUI, depending on which entry is selected in the QComboBox. I have managed to do that so far.
My problem is that all changes are taken into effect only when I press the "Run" button, which executes the application.
What I want to do is the action of enabling/disabling the relevant boxes will happen once I have selected the entry from the drop-down menu and not waiting until I press the "Run" button.
Is there a way to do something like that? Can I use the focusOutEvent to check when the user has clicked anywhere else than the drop-menu and apply the changes in the other boxes/labels?
I put below the class "controlling" my GUI, but I dont post the actual class generating the GUI because it is too lengthy. If you think it is relevant I can post it. I post instead a picture of the GUI.GUI The boxes and labels in the black circles should be disabled when the "Measuring Mode" drop-box is set to "Cable loss" or "Amplifier". When it is set to "Mixer" they should be enabled. I enable/disable the boxes and labels with an if statement inside the user_input function, in the Window class. The wanted drop-down menu is represeted by the "mode_select" variable.
Edit:
I think my explanation is not very intuitive without the actual gui code so I post it below.
from PyQt5 import QtWidgets, QtCore
from converter import convert_ui
import sys
import os
import time
class Window(QtWidgets.QMainWindow):
def __init__(self):
from transfer_function_gui import Ui_MainWindow
QtWidgets.QMainWindow.__init__(self)
self.ui = Ui_MainWindow()
self.ui.setupUi(self) # setup GUI
self.ui.run_button_PM_tab.clicked.connect(self.user_input)
def user_input(self):
test_mode = self.ui.mode_select.currentText() # type: str
if test_mode == "Mixer":
self.ui.LO_Power_input.setEnabled(True)
self.ui.LO_Power_lbl.setEnabled(True)
self.ui.LO_freq_input.setEnabled(True)
self.ui.LO_freq_lbl.setEnabled(True)
else:
self.ui.LO_Power_input.setEnabled(False)
self.ui.LO_Power_lbl.setEnabled(False)
self.ui.LO_freq_input.setEnabled(False)
self.ui.LO_freq_lbl.setEnabled(False)
############################### Main ###############################
if __name__=='__main__':
convert_ui('transfer_function_gui.ui')
app = QtWidgets.QApplication(sys.argv)
app.setStyle('Fusion')
window = Window()
window.show()
sys.exit(app.exec_())
GUI generation (from Qt designer)
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.setEnabled(True)
MainWindow.resize(770, 613)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.progressBar = QtWidgets.QProgressBar(self.centralwidget)
self.progressBar.setGeometry(QtCore.QRect(10, 520, 630, 30))
self.progressBar.setProperty("value", 0)
self.progressBar.setObjectName("progressBar")
self.Dev_address_frame = QtWidgets.QGroupBox(self.centralwidget)
self.Dev_address_frame.setGeometry(QtCore.QRect(10, 10, 371, 140))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Maximum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.Dev_address_frame.sizePolicy().hasHeightForWidth())
self.Dev_address_frame.setSizePolicy(sizePolicy)
self.Dev_address_frame.setMinimumSize(QtCore.QSize(0, 100))
font = QtGui.QFont()
font.setPointSize(8)
self.Dev_address_frame.setFont(font)
self.Dev_address_frame.setFlat(False)
self.Dev_address_frame.setCheckable(False)
self.Dev_address_frame.setObjectName("Dev_address_frame")
self.SigGen_label = QtWidgets.QLabel(self.Dev_address_frame)
self.SigGen_label.setGeometry(QtCore.QRect(20, 30, 100, 20))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Maximum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.SigGen_label.sizePolicy().hasHeightForWidth())
self.SigGen_label.setSizePolicy(sizePolicy)
self.SigGen_label.setObjectName("SigGen_label")
self.PM_label = QtWidgets.QLabel(self.Dev_address_frame)
self.PM_label.setGeometry(QtCore.QRect(20, 70, 100, 20))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Maximum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.PM_label.sizePolicy().hasHeightForWidth())
self.PM_label.setSizePolicy(sizePolicy)
self.PM_label.setObjectName("PM_label")
self.SigGen_addr_input = QtWidgets.QLineEdit(self.Dev_address_frame)
self.SigGen_addr_input.setGeometry(QtCore.QRect(120, 30, 180, 20))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Maximum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.SigGen_addr_input.sizePolicy().hasHeightForWidth())
self.SigGen_addr_input.setSizePolicy(sizePolicy)
self.SigGen_addr_input.setObjectName("SigGen_addr_input")
self.PM_addr_input = QtWidgets.QLineEdit(self.Dev_address_frame)
self.PM_addr_input.setGeometry(QtCore.QRect(120, 70, 180, 20))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Maximum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.PM_addr_input.sizePolicy().hasHeightForWidth())
self.PM_addr_input.setSizePolicy(sizePolicy)
self.PM_addr_input.setObjectName("PM_addr_input")
self.PM_cnct_checkBox = QtWidgets.QCheckBox(self.Dev_address_frame)
self.PM_cnct_checkBox.setEnabled(False)
self.PM_cnct_checkBox.setGeometry(QtCore.QRect(240, 105, 16, 20))
self.PM_cnct_checkBox.setText("")
self.PM_cnct_checkBox.setObjectName("PM_cnct_checkBox")
self.PM_cnct_lbl = QtWidgets.QLabel(self.Dev_address_frame)
self.PM_cnct_lbl.setEnabled(False)
self.PM_cnct_lbl.setGeometry(QtCore.QRect(20, 105, 210, 20))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Maximum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.PM_cnct_lbl.sizePolicy().hasHeightForWidth())
self.PM_cnct_lbl.setSizePolicy(sizePolicy)
self.PM_cnct_lbl.setObjectName("PM_cnct_lbl")
self.Freq_setup_frame = QtWidgets.QGroupBox(self.centralwidget)
self.Freq_setup_frame.setGeometry(QtCore.QRect(10, 200, 370, 181))
font = QtGui.QFont()
font.setPointSize(8)
self.Freq_setup_frame.setFont(font)
self.Freq_setup_frame.setFlat(False)
self.Freq_setup_frame.setCheckable(False)
self.Freq_setup_frame.setObjectName("Freq_setup_frame")
self.Start_freq_lbl = QtWidgets.QLabel(self.Freq_setup_frame)
self.Start_freq_lbl.setEnabled(True)
self.Start_freq_lbl.setGeometry(QtCore.QRect(20, 30, 100, 20))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.Start_freq_lbl.sizePolicy().hasHeightForWidth())
self.Start_freq_lbl.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(8)
self.Start_freq_lbl.setFont(font)
self.Start_freq_lbl.setMidLineWidth(0)
self.Start_freq_lbl.setText("Start freq. ")
self.Start_freq_lbl.setObjectName("Start_freq_lbl")
self.Stop_freq_lbl = QtWidgets.QLabel(self.Freq_setup_frame)
self.Stop_freq_lbl.setGeometry(QtCore.QRect(20, 70, 100, 20))
font = QtGui.QFont()
font.setPointSize(8)
self.Stop_freq_lbl.setFont(font)
self.Stop_freq_lbl.setObjectName("Stop_freq_lbl")
self.Step_freq_lbl = QtWidgets.QLabel(self.Freq_setup_frame)
self.Step_freq_lbl.setGeometry(QtCore.QRect(20, 110, 100, 20))
font = QtGui.QFont()
font.setPointSize(8)
self.Step_freq_lbl.setFont(font)
self.Step_freq_lbl.setObjectName("Step_freq_lbl")
self.StopFreq_input = QtWidgets.QLineEdit(self.Freq_setup_frame)
self.StopFreq_input.setGeometry(QtCore.QRect(120, 70, 180, 20))
font = QtGui.QFont()
font.setPointSize(8)
self.StopFreq_input.setFont(font)
self.StopFreq_input.setText("")
self.StopFreq_input.setObjectName("StopFreq_input")
self.Start_freq_input = QtWidgets.QLineEdit(self.Freq_setup_frame)
self.Start_freq_input.setGeometry(QtCore.QRect(120, 30, 180, 20))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Maximum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.Start_freq_input.sizePolicy().hasHeightForWidth())
self.Start_freq_input.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(8)
self.Start_freq_input.setFont(font)
self.Start_freq_input.setText("")
self.Start_freq_input.setObjectName("Start_freq_input")
self.StepFreq_input = QtWidgets.QLineEdit(self.Freq_setup_frame)
self.StepFreq_input.setGeometry(QtCore.QRect(120, 110, 180, 20))
font = QtGui.QFont()
font.setPointSize(8)
self.StepFreq_input.setFont(font)
self.StepFreq_input.setText("")
self.StepFreq_input.setObjectName("StepFreq_input")
self.freq_units_select = QtWidgets.QComboBox(self.Freq_setup_frame)
self.freq_units_select.setGeometry(QtCore.QRect(310, 29, 51, 141))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.freq_units_select.sizePolicy().hasHeightForWidth())
self.freq_units_select.setSizePolicy(sizePolicy)
self.freq_units_select.setMinimumSize(QtCore.QSize(0, 70))
font = QtGui.QFont()
font.setPointSize(8)
self.freq_units_select.setFont(font)
self.freq_units_select.setInsertPolicy(QtWidgets.QComboBox.InsertAtBottom)
self.freq_units_select.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContentsOnFirstShow)
self.freq_units_select.setFrame(True)
self.freq_units_select.setObjectName("freq_units_select")
self.freq_units_select.addItem("")
self.freq_units_select.addItem("")
self.freq_units_select.addItem("")
self.LO_freq_lbl = QtWidgets.QLabel(self.Freq_setup_frame)
self.LO_freq_lbl.setGeometry(QtCore.QRect(20, 150, 100, 20))
font = QtGui.QFont()
font.setPointSize(8)
self.LO_freq_lbl.setFont(font)
self.LO_freq_lbl.setObjectName("LO_freq_lbl")
self.LO_freq_input = QtWidgets.QLineEdit(self.Freq_setup_frame)
self.LO_freq_input.setGeometry(QtCore.QRect(120, 150, 180, 20))
font = QtGui.QFont()
font.setPointSize(8)
self.LO_freq_input.setFont(font)
self.LO_freq_input.setText("")
self.LO_freq_input.setObjectName("LO_freq_input")
self.Power_setup_frame = QtWidgets.QGroupBox(self.centralwidget)
self.Power_setup_frame.setGeometry(QtCore.QRect(10, 390, 370, 111))
font = QtGui.QFont()
font.setPointSize(8)
self.Power_setup_frame.setFont(font)
self.Power_setup_frame.setFlat(False)
self.Power_setup_frame.setCheckable(False)
self.Power_setup_frame.setObjectName("Power_setup_frame")
self.DUT_input_lbl = QtWidgets.QLabel(self.Power_setup_frame)
self.DUT_input_lbl.setGeometry(QtCore.QRect(20, 30, 100, 20))
font = QtGui.QFont()
font.setPointSize(8)
self.DUT_input_lbl.setFont(font)
self.DUT_input_lbl.setObjectName("DUT_input_lbl")
self.LO_Power_lbl = QtWidgets.QLabel(self.Power_setup_frame)
self.LO_Power_lbl.setGeometry(QtCore.QRect(20, 70, 100, 20))
font = QtGui.QFont()
font.setPointSize(8)
self.LO_Power_lbl.setFont(font)
self.LO_Power_lbl.setObjectName("LO_Power_lbl")
self.DUT_Input_power_input = QtWidgets.QLineEdit(self.Power_setup_frame)
self.DUT_Input_power_input.setGeometry(QtCore.QRect(120, 30, 180, 20))
font = QtGui.QFont()
font.setPointSize(8)
self.DUT_Input_power_input.setFont(font)
self.DUT_Input_power_input.setText("")
self.DUT_Input_power_input.setObjectName("DUT_Input_power_input")
self.LO_Power_input = QtWidgets.QLineEdit(self.Power_setup_frame)
self.LO_Power_input.setGeometry(QtCore.QRect(120, 70, 180, 20))
font = QtGui.QFont()
font.setPointSize(8)
self.LO_Power_input.setFont(font)
self.LO_Power_input.setText("")
self.LO_Power_input.setObjectName("LO_Power_input")
self.LO_dBm = QtWidgets.QLabel(self.Power_setup_frame)
self.LO_dBm.setGeometry(QtCore.QRect(320, 70, 20, 20))
font = QtGui.QFont()
font.setPointSize(8)
self.LO_dBm.setFont(font)
self.LO_dBm.setObjectName("LO_dBm")
self.DUT_dBm = QtWidgets.QLabel(self.Power_setup_frame)
self.DUT_dBm.setGeometry(QtCore.QRect(320, 30, 20, 20))
font = QtGui.QFont()
font.setPointSize(8)
self.DUT_dBm.setFont(font)
self.DUT_dBm.setObjectName("DUT_dBm")
self.mode_label = QtWidgets.QLabel(self.centralwidget)
self.mode_label.setGeometry(QtCore.QRect(30, 165, 100, 20))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.mode_label.sizePolicy().hasHeightForWidth())
self.mode_label.setSizePolicy(sizePolicy)
self.mode_label.setBaseSize(QtCore.QSize(0, 0))
self.mode_label.setObjectName("mode_label")
self.mode_select = QtWidgets.QComboBox(self.centralwidget)
self.mode_select.setGeometry(QtCore.QRect(130, 165, 180, 20))
self.mode_select.setObjectName("mode_select")
self.mode_select.addItem("")
self.mode_select.addItem("")
self.mode_select.addItem("")
self.run_button_PM_tab = QtWidgets.QPushButton(self.centralwidget)
self.run_button_PM_tab.setEnabled(True)
self.run_button_PM_tab.setGeometry(QtCore.QRect(650, 520, 100, 30))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.run_button_PM_tab.sizePolicy().hasHeightForWidth())
self.run_button_PM_tab.setSizePolicy(sizePolicy)
self.run_button_PM_tab.setMinimumSize(QtCore.QSize(0, 0))
self.run_button_PM_tab.setLayoutDirection(QtCore.Qt.LeftToRight)
self.run_button_PM_tab.setObjectName("run_button_PM_tab")
self.S21_table = QtWidgets.QTableWidget(self.centralwidget)
self.S21_table.setGeometry(QtCore.QRect(400, 10, 360, 490))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(33)
sizePolicy.setVerticalStretch(25)
sizePolicy.setHeightForWidth(self.S21_table.sizePolicy().hasHeightForWidth())
self.S21_table.setSizePolicy(sizePolicy)
self.S21_table.setMinimumSize(QtCore.QSize(15, 35))
self.S21_table.setSizeIncrement(QtCore.QSize(0, 0))
self.S21_table.setBaseSize(QtCore.QSize(0, 0))
self.S21_table.setObjectName("S21_table")
self.S21_table.setColumnCount(2)
self.S21_table.setRowCount(1)
item = QtWidgets.QTableWidgetItem()
self.S21_table.setVerticalHeaderItem(0, item)
item = QtWidgets.QTableWidgetItem()
item.setTextAlignment(QtCore.Qt.AlignCenter)
self.S21_table.setHorizontalHeaderItem(0, item)
item = QtWidgets.QTableWidgetItem()
self.S21_table.setHorizontalHeaderItem(1, item)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 770, 21))
self.menubar.setObjectName("menubar")
self.menuFile = QtWidgets.QMenu(self.menubar)
self.menuFile.setObjectName("menuFile")
self.menuAbout = QtWidgets.QMenu(self.menubar)
self.menuAbout.setObjectName("menuAbout")
self.menuPreferences = QtWidgets.QMenu(self.menubar)
self.menuPreferences.setObjectName("menuPreferences")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.actionSave_as = QtWidgets.QAction(MainWindow)
self.actionSave_as.setObjectName("actionSave_as")
self.actionExit = QtWidgets.QAction(MainWindow)
self.actionExit.setObjectName("actionExit")
self.menuFile.addAction(self.actionSave_as)
self.menuFile.addAction(self.actionExit)
self.menubar.addAction(self.menuFile.menuAction())
self.menubar.addAction(self.menuPreferences.menuAction())
self.menubar.addAction(self.menuAbout.menuAction())
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "Transfer Function Calculator v0.5"))
self.Dev_address_frame.setTitle(_translate("MainWindow", "Device addresses (GPIB, USB, TCPIP)"))
self.SigGen_label.setText(_translate("MainWindow", "Signal Generator"))
self.PM_label.setText(_translate("MainWindow", "Power Meter"))
self.PM_cnct_lbl.setText(_translate("MainWindow", "If PM is connected to SigGen check the box"))
self.Freq_setup_frame.setTitle(_translate("MainWindow", "Frequency setup"))
self.Stop_freq_lbl.setText(_translate("MainWindow", "Stop freq."))
self.Step_freq_lbl.setText(_translate("MainWindow", "Step freq."))
self.freq_units_select.setCurrentText(_translate("MainWindow", "kHz"))
self.freq_units_select.setItemText(0, _translate("MainWindow", "kHz"))
self.freq_units_select.setItemText(1, _translate("MainWindow", "MHz"))
self.freq_units_select.setItemText(2, _translate("MainWindow", "GHz"))
self.LO_freq_lbl.setText(_translate("MainWindow", "LO freq."))
self.Power_setup_frame.setTitle(_translate("MainWindow", "Power setup"))
self.DUT_input_lbl.setText(_translate("MainWindow", "DUT Input power"))
self.LO_Power_lbl.setText(_translate("MainWindow", "LO Power"))
self.LO_dBm.setText(_translate("MainWindow", "dBm"))
self.DUT_dBm.setText(_translate("MainWindow", "dBm"))
self.mode_label.setText(_translate("MainWindow", "Measuring mode"))
self.mode_select.setItemText(0, _translate("MainWindow", "Cable loss"))
self.mode_select.setItemText(1, _translate("MainWindow", "Amplifier"))
self.mode_select.setItemText(2, _translate("MainWindow", "Mixer"))
self.run_button_PM_tab.setText(_translate("MainWindow", "Run"))
item = self.S21_table.verticalHeaderItem(0)
item.setText(_translate("MainWindow", "New Row"))
item = self.S21_table.horizontalHeaderItem(0)
item.setText(_translate("MainWindow", "New Column"))
item = self.S21_table.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", "New Column"))
self.menuFile.setTitle(_translate("MainWindow", "File"))
self.menuAbout.setTitle(_translate("MainWindow", "About"))
self.menuPreferences.setTitle(_translate("MainWindow", "Settings..."))
self.actionSave_as.setText(_translate("MainWindow", "Save as..."))
self.actionExit.setText(_translate("MainWindow", "Exit"))
QComboBox uses these signals here which you can connect using signals and slots.
I think the one you would want to use is either currentTextChanged or currentIndexChanged. So you could do something like this in your init:
class Window(QtWidgets.QMainWindow):
def __init__(self):
from transfer_function_gui import Ui_MainWindow
QtWidgets.QMainWindow.__init__(self)
self.ui = Ui_MainWindow()
self.ui.setupUi(self) # setup GUI
self.ui.run_button_PM_tab.clicked.connect(self.user_input)
self.ui.freq_units_select.currentIndexChanged.connect(self.user_input)
self.ui.mode_select.currentIndexChanged.connect(self.user_input)
This will connect the event of the QComboBox changing it's selected index to a method called self.user_input.

How pass data from second window to main?

I have a python app that change mac address with pyqt5 GUI. I have two python files. The main python file (mainWindow.py) that run main program then I press button to open the second window from second python file secondWindow.py. In second python file opens a window entry then I have to put letters and numbers like then I have to pass data in the first main app label window.
Can anyone help me to solve that?
I tried to reduce code.
mainWindow.py
#!/usr/bin/python3
import os
import sys
import subprocess
from PyQt5 import QtCore, QtGui, QtWidgets
from secondWindow import Ui_macSpecific
import macspoof_bash
import settings
macspoof_bash.write_to_ini()
# Read and write settings in macspoof.ini file
from configparser import ConfigParser
# instantiate
config = ConfigParser()
# parse existing file
config.read('/home/user/.config/macspoof/macspoof.ini')
# read values from a section
wired = config.get('ethernet', 'wired')
wireless = config.get('wifi', 'wireless')
class Ui_MainWindow(object):
def specificWindow(self):
self.window = QtWidgets.QDialog()
self.ui = Ui_macSpecific()
#self.ui.setupUi(self.window)
self.ui.setupUi(self.window, self) # <--- assign MainWindow as parent to second window
self.window.show()
def aboutWindow(self):
self.aboutWindow = QtWidgets.QDialog()
self.ui = Ui_Dialog()
self.ui.setupUi(self.aboutWindow)
self.aboutWindow.show()
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(480, 400)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout.setObjectName("gridLayout")
self.label_3 = QtWidgets.QLabel(self.centralwidget)
self.label_3.setStyleSheet("background-color: rgb(36, 31, 49);\n"
"font: 11pt \"DejaVu Sans\";\n"
"color: rgb(246, 245, 244);")
self.label_3.setAlignment(QtCore.Qt.AlignCenter)
self.label_3.setObjectName("label_3")
self.gridLayout.addWidget(self.label_3, 1, 0, 1, 1)
self.pushButton_6 = QtWidgets.QPushButton(self.centralwidget, clicked = lambda: self.specificWindow())
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton_6.sizePolicy().hasHeightForWidth())
self.pushButton_6.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setFamily("DejaVu Sans")
font.setPointSize(10)
self.pushButton_6.setFont(font)
self.pushButton_6.setObjectName("pushButton_6")
self.gridLayout.addWidget(self.pushButton_6, 4, 1, 1, 1)
self.pushButton = QtWidgets.QPushButton(self.centralwidget, clicked = lambda: self.button_vendor_wired())
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton.sizePolicy().hasHeightForWidth())
self.pushButton.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setFamily("DejaVu Sans")
font.setPointSize(10)
self.pushButton.setFont(font)
self.pushButton.setObjectName("pushButton")
self.gridLayout.addWidget(self.pushButton, 2, 0, 1, 1)
self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget, clicked = lambda: self.button_fully_wired())
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton_3.sizePolicy().hasHeightForWidth())
self.pushButton_3.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setFamily("DejaVu Sans")
font.setPointSize(10)
self.pushButton_3.setFont(font)
self.pushButton_3.setObjectName("pushButton_3")
self.gridLayout.addWidget(self.pushButton_3, 3, 0, 1, 1)
self.pushButton_8 = QtWidgets.QPushButton(self.centralwidget, clicked = lambda: self.button_original_wireless())
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton_8.sizePolicy().hasHeightForWidth())
self.pushButton_8.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setFamily("DejaVu Sans")
font.setPointSize(10)
self.pushButton_8.setFont(font)
self.pushButton_8.setLayoutDirection(QtCore.Qt.LeftToRight)
self.pushButton_8.setAutoFillBackground(False)
self.pushButton_8.setObjectName("pushButton_8")
self.gridLayout.addWidget(self.pushButton_8, 5, 1, 1, 1)
self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget, clicked = lambda: self.button_vendor_wireless())
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton_2.sizePolicy().hasHeightForWidth())
self.pushButton_2.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setFamily("DejaVu Sans")
font.setPointSize(10)
self.pushButton_2.setFont(font)
self.pushButton_2.setObjectName("pushButton_2")
self.gridLayout.addWidget(self.pushButton_2, 2, 1, 1, 1)
self.pushButton_7 = QtWidgets.QPushButton(self.centralwidget, clicked = lambda: self.button_original_wired())
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton_7.sizePolicy().hasHeightForWidth())
self.pushButton_7.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setFamily("DejaVu Sans")
font.setPointSize(10)
self.pushButton_7.setFont(font)
self.pushButton_7.setObjectName("pushButton_7")
self.gridLayout.addWidget(self.pushButton_7, 5, 0, 1, 1)
self.pushButton_5 = QtWidgets.QPushButton(self.centralwidget, clicked = lambda: self.specificWindow())
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton_5.sizePolicy().hasHeightForWidth())
self.pushButton_5.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setFamily("DejaVu Sans")
font.setPointSize(10)
self.pushButton_5.setFont(font)
self.pushButton_5.setObjectName("pushButton_5")
self.gridLayout.addWidget(self.pushButton_5, 4, 0, 1, 1)
self.label_4 = QtWidgets.QLabel(self.centralwidget)
self.label_4.setStyleSheet("background-color: rgb(36, 31, 49);\n"
"font: 11pt \"DejaVu Sans\";\n"
"color: rgb(246, 245, 244);")
self.label_4.setObjectName("label_4")
self.label_4.setAlignment(QtCore.Qt.AlignCenter)
self.gridLayout.addWidget(self.label_4, 1, 1, 1, 1)
self.pushButton_4 = QtWidgets.QPushButton(self.centralwidget, clicked = lambda: self.button_fully_wireless())
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton_4.sizePolicy().hasHeightForWidth())
self.pushButton_4.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setFamily("DejaVu Sans")
font.setPointSize(10)
self.pushButton_4.setFont(font)
self.pushButton_4.setObjectName("pushButton_4")
self.gridLayout.addWidget(self.pushButton_4, 3, 1, 1, 1)
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setMinimumSize(QtCore.QSize(0, 0))
self.label.setSizeIncrement(QtCore.QSize(0, 0))
self.label.setStyleSheet("background-color: rgb(36, 31, 49);\n"
"font: 11pt \"DejaVu Sans\";\n"
"color: rgb(246, 245, 244);")
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setObjectName("label")
self.gridLayout.addWidget(self.label, 0, 0, 1, 1)
self.label_2 = QtWidgets.QLabel(self.centralwidget)
self.label_2.setStyleSheet("background-color: rgb(36, 31, 49);\n"
"font: 11pt \"DejaVu Sans\";\n"
"color: rgb(246, 245, 244);")
self.label_2.setObjectName("label_2")
self.label_2.setAlignment(QtCore.Qt.AlignCenter)
self.gridLayout.addWidget(self.label_2, 0, 1, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 480, 20))
self.menubar.setObjectName("menubar")
self.menuFile = QtWidgets.QMenu(self.menubar)
self.menuFile.setObjectName("menuFile")
self.menuEdit = QtWidgets.QMenu(self.menubar)
self.menuEdit.setObjectName("menuEdit")
self.menuHelp = QtWidgets.QMenu(self.menubar)
self.menuHelp.setObjectName("menuHelp")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.actionExit = QtWidgets.QAction(MainWindow)
self.actionExit.triggered.connect(lambda: self.close_window())
self.actionExit.setObjectName("actionExit")
self.actionPreferences = QtWidgets.QAction(MainWindow)
self.actionPreferences.setObjectName("actionPreferences")
self.actionAbout = QtWidgets.QAction(MainWindow)
self.actionAbout.triggered.connect(lambda: self.aboutWindow())
self.actionAbout.setObjectName("actionAbout")
self.menuFile.addAction(self.actionExit)
self.menuEdit.addAction(self.actionPreferences)
self.menuHelp.addAction(self.actionAbout)
self.menubar.addAction(self.menuFile.menuAction())
self.menubar.addAction(self.menuEdit.menuAction())
self.menubar.addAction(self.menuHelp.menuAction())
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
self.update_wired_label(MainWindow)
self.update_wired_mac_address_label(MainWindow)
self.update_wireless_label(MainWindow)
self.update_wireless_mac_address_label(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MAC address spoofing"))
self.label_3.setText(_translate("MainWindow", "TextLabel"))
self.pushButton_6.setText(_translate("MainWindow", "Set the MAC"))
self.pushButton.setText(_translate("MainWindow", "Don\'t change vendor bytes"))
self.pushButton_3.setText(_translate("MainWindow", "Set fully random MAC"))
self.pushButton_8.setText(_translate("MainWindow", "Reset MAC address to its original"))
self.pushButton_2.setText(_translate("MainWindow", "Don\'t change vendor bytes"))
self.pushButton_7.setText(_translate("MainWindow", "Reset MAC address to its original"))
self.pushButton_5.setText(_translate("MainWindow", "Set the MAC"))
self.label_4.setText(_translate("MainWindow", "TextLabel"))
self.pushButton_4.setText(_translate("MainWindow", "Set fully random MAC"))
self.label.setText(_translate("MainWindow", "TextLabel"))
self.label_2.setText(_translate("MainWindow", "TextLabel"))
self.menuFile.setTitle(_translate("MainWindow", "File"))
self.menuEdit.setTitle(_translate("MainWindow", "Settings"))
self.menuHelp.setTitle(_translate("MainWindow", "Help"))
self.actionExit.setText(_translate("MainWindow", "Exit"))
self.actionPreferences.setText(_translate("MainWindow", "Preferences"))
self.actionAbout.setText(_translate("MainWindow", "About"))
def update_wired_label(self, MainWindow):
print('update_wired_label')
self.wired = config.get('ethernet', 'wired')
self.label.setText(str(self.wired))
def update_wired_mac_address_label(self, MainWindow):
print('update_wired_mac_address_label')
config.read('/home/user/.config/macspoof/macspoof.ini')
self.wired_mac_address = config.get('ethernet', 'wired_mac_address')
self.label_3.setText(str(self.wired_mac_address))
def update_wireless_label(self, MainWindow):
print('update_wireless_label')
self.wireless = config.get('wifi', 'wireless')
self.label_2.setText(str(self.wireless))
def update_wireless_mac_address_label(self, MainWindow):
print('update_wireless_mac_address_label')
config.read('/home/user/.config/macspoof/macspoof.ini')
self.wireless_mac_address = config.get('wifi', 'wireless_mac_address')
self.label_4.setText(str(self.wireless_mac_address))
def button_vendor_wired(self):
print('vendor_wired')
subprocess.run(['macchanger', '-e', wired])
macspoof_bash.vendor_wired()
self.update_wired_mac_address_label(MainWindow)
def button_fully_wired(self):
print('fully wired')
subprocess.run(['macchanger', '-r', wired])
macspoof_bash.write_to_ini()
self.update_wired_mac_address_label(MainWindow)
#def button_specific_wired(self):
# print('specific wired')
# subprocess.run(["macchanger", "-m", wired])
def button_original_wired(self):
print('original wired')
subprocess.run(['macchanger', '-p', wired])
macspoof_bash.write_to_ini()
self.update_wired_mac_address_label(MainWindow)
def button_vendor_wireless(self):
print('vendor_wireless')
subprocess.run(['macchanger', '-e', wireless])
macspoof_bash.vendor_wireless()
self.update_wireless_mac_address_label(MainWindow)
def button_fully_wireless(self):
print('fully wireless')
#wireless = config.get("wifi", "wireless")
#subprocess.run(['macchanger', '-r', wired])
macspoof_bash.fully_wireless()
self.update_wireless_mac_address_label(MainWindow)
def button_specific_wireless(self):
print('specific wired')
subprocess.run(["macchanger", "-m", wireless])
def button_original_wireless(self):
print('original wireless')
subprocess.run(['macchanger', '-p', wireless])
macspoof_bash.write_to_ini()
self.update_wireless_mac_address_label(MainWindow)
def close_window(self):
print("Quit")
sys.exit()
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_())
secondWindow.py
from PyQt5 import QtCore, QtGui, QtWidgets
# Read and write settings in macspoof.ini file
from configparser import ConfigParser
# instantiate
config = ConfigParser()
# parse existing file
config.read('macspoof.ini')
# read values from a section
wired = config.get('ethernet', 'wired')
wired_mac_address = config.get('ethernet', 'wired_mac_address')
class Ui_macSpecific(object):
def setupUi(self, macSpecific, parent): # <--- add extra parameter parent
self.parent = parent # < --- create new attribute parent
#def setupUi(self, macSpecific):
macSpecific.setObjectName("macSpecific")
macSpecific.resize(301, 140)
self.gridLayout = QtWidgets.QGridLayout(macSpecific)
self.gridLayout.setObjectName("gridLayout")
self.label = QtWidgets.QLabel(macSpecific)
font = QtGui.QFont()
font.setFamily("DejaVu Sans")
font.setPointSize(10)
self.label.setFont(font)
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setObjectName("label")
self.gridLayout.addWidget(self.label, 0, 0, 1, 1)
self.lineEdit = QtWidgets.QLineEdit(macSpecific)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.lineEdit.sizePolicy().hasHeightForWidth())
self.lineEdit.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setFamily("DejaVu Sans")
font.setPointSize(14)
self.lineEdit.setFont(font)
self.lineEdit.setLayoutDirection(QtCore.Qt.LeftToRight)
self.lineEdit.setAutoFillBackground(False)
self.lineEdit.setAlignment(QtCore.Qt.AlignCenter)
self.lineEdit.setObjectName("lineEdit")
self.gridLayout.addWidget(self.lineEdit, 1, 0, 1, 1)
self.pushButton = QtWidgets.QPushButton(macSpecific, clicked = lambda: self.submit())
self.pushButton.setObjectName("pushButton")
self.gridLayout.addWidget(self.pushButton, 2, 0, 1, 1)
self.retranslateUi(macSpecific)
QtCore.QMetaObject.connectSlotsByName(macSpecific)
def retranslateUi(self, macSpecific):
_translate = QtCore.QCoreApplication.translate
macSpecific.setWindowTitle(_translate("macSpecific", "MAC address spoofing"))
self.label.setText(_translate("macSpecific", "Enter A MAC address"))
self.lineEdit.setText(_translate("macSpecific", "11:22:33:44:55:66"))
self.pushButton.setText(_translate("macSpecific", "Submit"))
def submit(self):
print("submit")
#self.parent.label_3.setText(str(self.wired_mac_address)) # use parent to set label text
self.parent.label_3.setText(str(self.parent.wired_mac_address)) # <-----Try this then.
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
macSpecific = QtWidgets.QDialog()
ui = Ui_macSpecific()
ui.setupUi(macSpecific)
macSpecific.show()
sys.exit(app.exec_())
One solution would be to assign the MainWindow as the parent of the SecondWindow. Then to get the label text all the SecondWindow has to do is self.parent.label.setText('something'). See the minor adjustments I made below.
mainWindow.py
class Ui_MainWindow(object):
def specificWindow(self):
self.window = QtWidgets.QDialog()
self.ui = Ui_macSpecific()
self.ui.setupUi(self.window, self) # <--- assign MainWindow as parent to second window
self.window.show()
secondWindow.py
import macspoof_bash
class Ui_macSpecific(object):
def setupUi(self, macSpecific, master):
self.master = master
self.window = macSpecific
macSpecific.setObjectName("macSpecific")
macSpecific.resize(301, 140)
...
...
self.pushButton = QtWidgets.QPushButton(macSpecific, clicked = lambda: self.submit())
def submit(self):
print("submit")
text = self.lineEdit.text()
self.master.label_3.setText(text)
self.window.close()
config['ethernet']['wired_mac_address'] = text
with open("macspoof.ini", "w") as inifile:
config.write(inifile)

How to connect python script to a button in PyQt5?

I was trying to create a GUI for a desktop application and from one window I wanted to connect one of the buttons to another script, actually it is working fine except the function which responsible of clothing the second window "exit_popup_message" in update_window.py
so I run the first file successfully and click on "update user" button it runs the second window successfully but whenever I click on exit in the second window it crashes and gives this error:
Process finished with exit code -1073740791 (0xC0000409)
update_window.py:
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMessageBox
from PyQt5.QtCore import QDate
import sys
class Ui_UpdatePage(object):
def setupUi(self, UpdatePage):
#Update page
UpdatePage.setObjectName("UpdatePage")
UpdatePage.setEnabled(True)
UpdatePage.setFixedSize(400, 350)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Maximum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(UpdatePage.sizePolicy().hasHeightForWidth())
UpdatePage.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(10)
UpdatePage.setFont(font)
UpdatePage.setFocusPolicy(QtCore.Qt.StrongFocus)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("D:/FIU/Graduation project/covid_tracer/regist_icon.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
UpdatePage.setWindowIcon(icon)
UpdatePage.setWindowOpacity(100.0)
UpdatePage.setAutoFillBackground(True)
UpdatePage.setDocumentMode(True)
UpdatePage.setTabShape(QtWidgets.QTabWidget.Rounded)
self.centralwidget = QtWidgets.QWidget(UpdatePage)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(40, 20, 320, 300))
self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
self.verticalLayout.setContentsMargins(0, 0, 0, 0)
self.verticalLayout.setObjectName("verticalLayout")
self.formLayout = QtWidgets.QFormLayout()
self.formLayout.setObjectName("formLayout")
#Registration Form Label
self.reg_label = QtWidgets.QLabel(self.verticalLayoutWidget)
font = QtGui.QFont()
font.setPointSize(20)
font.setBold(True)
font.setWeight(75)
self.reg_label.setFont(font)
self.reg_label.setLayoutDirection(QtCore.Qt.LeftToRight)
self.reg_label.setAlignment(QtCore.Qt.AlignCenter)
self.reg_label.setObjectName("reg_label")
self.formLayout.setWidget(1, QtWidgets.QFormLayout.SpanningRole, self.reg_label)
#ID Number
self.id_label = QtWidgets.QLabel(self.verticalLayoutWidget)
font = QtGui.QFont()
font.setPointSize(10)
self.id_label.setFont(font)
self.id_label.setObjectName("id_label")
self.formLayout.setWidget(3, QtWidgets.QFormLayout.LabelRole, self.id_label)
self.id_input = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.id_input.setStyleSheet("id_input->rgb(191, 126, 255)")
self.id_input.setFrame(True)
self.id_input.setEchoMode(QtWidgets.QLineEdit.Normal)
self.id_input.setCursorPosition(0)
self.id_input.setDragEnabled(False)
self.id_input.setReadOnly(False)
self.id_input.setClearButtonEnabled(False)
self.id_input.setObjectName("id_input")
self.formLayout.setWidget(3, QtWidgets.QFormLayout.FieldRole, self.id_input)
#Phone Number
self.phone_label = QtWidgets.QLabel(self.verticalLayoutWidget)
font = QtGui.QFont()
font.setPointSize(10)
self.phone_label.setFont(font)
self.phone_label.setObjectName("phone_label")
self.formLayout.setWidget(5, QtWidgets.QFormLayout.LabelRole, self.phone_label)
self.phone_input = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.phone_input.setObjectName("phone_input")
self.formLayout.setWidget(5, QtWidgets.QFormLayout.FieldRole, self.phone_input)
#Name & Surname
self.name_label = QtWidgets.QLabel(self.verticalLayoutWidget)
font = QtGui.QFont()
font.setPointSize(10)
self.name_label.setFont(font)
self.name_label.setObjectName("name_label")
self.formLayout.setWidget(6, QtWidgets.QFormLayout.LabelRole, self.name_label)
self.name_input = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.name_input.setObjectName("name_input")
self.formLayout.setWidget(6, QtWidgets.QFormLayout.FieldRole, self.name_input)
self.SuName_label = QtWidgets.QLabel(self.verticalLayoutWidget)
font = QtGui.QFont()
font.setPointSize(10)
self.SuName_label.setFont(font)
self.SuName_label.setObjectName("SuName_label")
self.formLayout.setWidget(8, QtWidgets.QFormLayout.LabelRole, self.SuName_label)
self.SuName_input = QtWidgets.QLineEdit(self.verticalLayoutWidget)
self.SuName_input.setObjectName("SuName_input")
self.formLayout.setWidget(8, QtWidgets.QFormLayout.FieldRole, self.SuName_input)
#Date of birth
self.DOB_label = QtWidgets.QLabel(self.verticalLayoutWidget)
font = QtGui.QFont()
font.setPointSize(10)
self.DOB_label.setFont(font)
self.DOB_label.setObjectName("DOB_label")
self.formLayout.setWidget(9, QtWidgets.QFormLayout.LabelRole, self.DOB_label)
self.DOB_input = QtWidgets.QDateEdit(self.verticalLayoutWidget)
self.DOB_input.setObjectName("DOB_input")
self.formLayout.setWidget(9, QtWidgets.QFormLayout.FieldRole, self.DOB_input)
#Gender
self.G_label = QtWidgets.QLabel(self.verticalLayoutWidget)
font = QtGui.QFont()
font.setPointSize(10)
self.G_label.setFont(font)
self.G_label.setObjectName("gender")
self.formLayout.setWidget(11, QtWidgets.QFormLayout.LabelRole, self.G_label)
self.gender = QtWidgets.QComboBox(self.verticalLayoutWidget)
self.gender.setObjectName("gender")
self.gender.addItem("")
self.gender.addItem("")
self.formLayout.setWidget(11, QtWidgets.QFormLayout.FieldRole, self.gender)
#Registration Date
self.regiDate_label = QtWidgets.QLabel(self.verticalLayoutWidget)
font = QtGui.QFont()
font.setPointSize(10)
self.regiDate_label.setFont(font)
self.regiDate_label.setObjectName("registrationDate_label")
self.formLayout.setWidget(12, QtWidgets.QFormLayout.LabelRole, self.regiDate_label)
self.regiDate_input = QtWidgets.QDateEdit(self.verticalLayoutWidget)
self.regiDate_input.setObjectName("regiDate_input")
self.formLayout.setWidget(12, QtWidgets.QFormLayout.FieldRole, self.regiDate_input)
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
#Save button
self.b1_save = QtWidgets.QPushButton(self.verticalLayoutWidget)
self.b1_save.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.b1_save.setStyleSheet("")
self.b1_save.setObjectName("b1_save")
self.horizontalLayout.addWidget(self.b1_save)
self.b1_save.clicked.connect(self.save_data)
self.b1_save.setDefault(False);
self.b1_save.setAutoDefault(True);
#exit button
self.b2_exit = QtWidgets.QPushButton(self.verticalLayoutWidget)
self.b2_exit.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.b2_exit.setObjectName("b2_cansel")
self.horizontalLayout.addWidget(self.b2_exit)
self.b2_exit.clicked.connect(self.exit_popup_message)
self.b2_exit.setDefault(False);
self.b2_exit.setAutoDefault(True);
self.formLayout.setLayout(16, QtWidgets.QFormLayout.SpanningRole, self.horizontalLayout)
spacerItem = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.formLayout.setItem(15, QtWidgets.QFormLayout.LabelRole, spacerItem)
self.verticalLayout.addLayout(self.formLayout)
UpdatePage.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(UpdatePage)
self.menubar.setGeometry(QtCore.QRect(0, 0, 398, 21))
self.menubar.setObjectName("menubar")
UpdatePage.setMenuBar(self.menubar)
self.retranslateUi(UpdatePage)
QtCore.QMetaObject.connectSlotsByName(UpdatePage)
UpdatePage.setTabOrder(self.id_input, self.phone_input)
UpdatePage.setTabOrder(self.phone_input, self.name_input)
UpdatePage.setTabOrder(self.name_input, self.SuName_input)
UpdatePage.setTabOrder(self.SuName_input, self.DOB_input)
UpdatePage.setTabOrder(self.DOB_input, self.gender)
UpdatePage.setTabOrder(self.gender, self.regiDate_input)
UpdatePage.setTabOrder(self.regiDate_input, self.b1_save)
UpdatePage.setTabOrder(self.b1_save, self.b2_exit)
def retranslateUi(self, UpdatePage):
_translate = QtCore.QCoreApplication.translate
UpdatePage.setWindowTitle(_translate("RegisterPage", "Update Form"))
self.reg_label.setText(_translate("RegisterPage", "User Update Form"))
self.id_label.setText(_translate("RegisterPage", "ID Number"))
self.phone_label.setText(_translate("RegisterPage", "Phone Number"))
self.name_label.setText(_translate("RegisterPage", "Name"))
self.SuName_label.setText(_translate("RegisterPage", "Surname"))
self.DOB_label.setText(_translate("RegisterPage", "Date Of Birth"))
self.G_label.setText(_translate("RegisterPage", "Gender"))
self.gender.setItemText(0, _translate("RegisterPage", "Male"))
self.gender.setItemText(1, _translate("RegisterPage", "Female"))
self.regiDate_label.setText(_translate("RegisterPage", "Registration Date"))
self.b1_save.setText(_translate("RegisterPage", "Save"))
self.b2_exit.setText(_translate("RegisterPage", "Exit"))
#Saving the input data
def save_data (self):
if self.id_input.text() == "" or self.phone_input.text() == "" or self.name_input.text() == "" or self.SuName_input.text() == "":
msg = QMessageBox()
msg.setWindowTitle("Warning!")
msg.setText("All fields must be filled!")
msg.setIcon(QMessageBox.Warning)
msg.setStandardButtons(QMessageBox.Ok)
x = msg.exec_()
else:
ID = self.id_input.text()
Phone = self.phone_input.text()
Name = self.name_input.text()
SurName = self.SuName_input.text()
date = self.DOB_input.date().toPyDate()
Gender = self.gender.currentText()
RegiDate = self.regiDate_input.date().toPyDate()
print(ID, Phone, Name, SurName, date, Gender, RegiDate)
msg = QMessageBox()
msg.setWindowTitle("Confirmation")
msg.setText("Data saved successfully!")
msg.setIcon(QMessageBox.Information)
x = msg.exec_()
if x == QMessageBox.Ok:
self.id_input.clear()
self.phone_input.clear()
self.name_input.clear()
self.SuName_input.clear()
self.DOB_input.setDate(QDate(2000, 1, 1))
self.regiDate_input.setDate(QDate(2000, 1, 1))
#Exit the window
def exit_popup_message (self):
msg = QMessageBox()
msg.setWindowTitle("Warning")
msg.setText("Are you sure you want to exit?")
msg.setIcon(QMessageBox.Question)
msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
x = msg.exec_()
if x == msg.Yes:
UpdatePage.close()
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
UpdatePage = QtWidgets.QMainWindow()
ui = Ui_UpdatePage()
ui.setupUi(UpdatePage)
UpdatePage.show()
sys.exit(app.exec_())
user_info.py:
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMessageBox
from update_window import Ui_UpdatePage
import sys
import update_window
class Ui_User_Info(object):
def setupUi(self, User_Info):
# User info page
User_Info.setObjectName("User_Info")
User_Info.setWindowModality(QtCore.Qt.NonModal)
User_Info.setFixedSize(522, 422)
User_Info.statusBar().setSizeGripEnabled(False)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Maximum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(User_Info.sizePolicy().hasHeightForWidth())
User_Info.setSizePolicy(sizePolicy)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("D:/FIU/Graduation project/covid_tracer/user_icon.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
User_Info.setWindowIcon(icon)
self.centralwidget = QtWidgets.QWidget(User_Info)
self.centralwidget.setObjectName("centralwidget")
self.verticalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(10, 0, 501, 191))
self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
self.verticalLayout.setContentsMargins(0, 0, 0, 0)
self.verticalLayout.setObjectName("verticalLayout")
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
# ID Number
self.id_label = QtWidgets.QLabel(self.verticalLayoutWidget)
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.id_label.setFont(font)
self.id_label.setObjectName("id_label")
self.horizontalLayout.addWidget(self.id_label)
self.id_output = QtWidgets.QLabel(self.verticalLayoutWidget)
self.id_output.setObjectName("id_output")
self.horizontalLayout.addWidget(self.id_output)
# Phone Number
self.Ph_label = QtWidgets.QLabel(self.verticalLayoutWidget)
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.Ph_label.setFont(font)
self.Ph_label.setObjectName("Ph_label")
self.horizontalLayout.addWidget(self.Ph_label)
self.Ph_output = QtWidgets.QLabel(self.verticalLayoutWidget)
self.Ph_output.setObjectName("Ph_output")
self.horizontalLayout.addWidget(self.Ph_output)
self.verticalLayout.addLayout(self.horizontalLayout)
self.horizontalLayout_4 = QtWidgets.QHBoxLayout()
self.horizontalLayout_4.setObjectName("horizontalLayout_4")
# Name & Surname
self.name_label = QtWidgets.QLabel(self.verticalLayoutWidget)
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.name_label.setFont(font)
self.name_label.setObjectName("name_label")
self.horizontalLayout_4.addWidget(self.name_label)
self.name_output = QtWidgets.QLabel(self.verticalLayoutWidget)
self.name_output.setObjectName("name_output")
self.horizontalLayout_4.addWidget(self.name_output)
self.SuName_label = QtWidgets.QLabel(self.verticalLayoutWidget)
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.SuName_label.setFont(font)
self.SuName_label.setObjectName("SuName_label")
self.horizontalLayout_4.addWidget(self.SuName_label)
self.SuName_output = QtWidgets.QLabel(self.verticalLayoutWidget)
self.SuName_output.setObjectName("SuName_output")
self.horizontalLayout_4.addWidget(self.SuName_output)
self.verticalLayout.addLayout(self.horizontalLayout_4)
self.horizontalLayout_5 = QtWidgets.QHBoxLayout()
self.horizontalLayout_5.setObjectName("horizontalLayout_5")
# Gender
self.G_label = QtWidgets.QLabel(self.verticalLayoutWidget)
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.G_label.setFont(font)
self.G_label.setObjectName("G_label")
self.horizontalLayout_5.addWidget(self.G_label)
self.G_output = QtWidgets.QLabel(self.verticalLayoutWidget)
self.G_output.setObjectName("G_output")
self.horizontalLayout_5.addWidget(self.G_output)
# Date Of Birth
self.DOB_label = QtWidgets.QLabel(self.verticalLayoutWidget)
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.DOB_label.setFont(font)
self.DOB_label.setObjectName("DOB_label")
self.horizontalLayout_5.addWidget(self.DOB_label)
self.DOB_output = QtWidgets.QLabel(self.verticalLayoutWidget)
self.DOB_output.setObjectName("DOB_output")
self.horizontalLayout_5.addWidget(self.DOB_output)
self.verticalLayout.addLayout(self.horizontalLayout_5)
self.horizontalLayout_10 = QtWidgets.QHBoxLayout()
self.horizontalLayout_10.setObjectName("horizontalLayout_10")
# Registration Date
self.regiDate_label = QtWidgets.QLabel(self.verticalLayoutWidget)
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.regiDate_label.setFont(font)
self.regiDate_label.setObjectName("regiDate_label")
self.horizontalLayout_10.addWidget(self.regiDate_label)
self.regiDate_output = QtWidgets.QLabel(self.verticalLayoutWidget)
self.regiDate_output.setObjectName("regiDate_output")
self.horizontalLayout_10.addWidget(self.regiDate_output)
spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_10.addItem(spacerItem)
self.verticalLayout.addLayout(self.horizontalLayout_10)
self.horizontalLayoutWidget_4 = QtWidgets.QWidget(self.centralwidget)
self.horizontalLayoutWidget_4.setGeometry(QtCore.QRect(10, 210, 501, 141))
self.horizontalLayoutWidget_4.setObjectName("horizontalLayoutWidget_4")
self.horizontalLayout_8 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget_4)
self.horizontalLayout_8.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout_8.setObjectName("horizontalLayout_8")
self.verticalLayout_2 = QtWidgets.QVBoxLayout()
self.verticalLayout_2.setObjectName("verticalLayout_2")
# PCR History
self.PCR_label = QtWidgets.QLabel(self.horizontalLayoutWidget_4)
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.PCR_label.setFont(font)
self.PCR_label.setObjectName("PCR_label")
self.verticalLayout_2.addWidget(self.PCR_label)
spacerItem1 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.verticalLayout_2.addItem(spacerItem1)
# Add Reocrd Button
self.b1_add = QtWidgets.QPushButton(self.horizontalLayoutWidget_4)
self.b1_add.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.b1_add.setObjectName("b1_add")
self.verticalLayout_2.addWidget(self.b1_add)
spacerItem2 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.verticalLayout_2.addItem(spacerItem2)
self.horizontalLayout_8.addLayout(self.verticalLayout_2)
# PCR Table
self.PCR_Table = QtWidgets.QTableWidget(self.horizontalLayoutWidget_4)
self.PCR_Table.setObjectName("PCR_Table")
self.PCR_Table.setColumnCount(2)
self.PCR_Table.setRowCount(0)
item = QtWidgets.QTableWidgetItem()
self.PCR_Table.setHorizontalHeaderItem(0, item)
item = QtWidgets.QTableWidgetItem()
self.PCR_Table.setHorizontalHeaderItem(1, item)
self.horizontalLayout_8.addWidget(self.PCR_Table)
self.horizontalLayoutWidget_5 = QtWidgets.QWidget(self.centralwidget)
self.horizontalLayoutWidget_5.setGeometry(QtCore.QRect(40, 350, 441, 51))
self.horizontalLayoutWidget_5.setObjectName("horizontalLayoutWidget_5")
self.horizontalLayout_9 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget_5)
self.horizontalLayout_9.setContentsMargins(0, 0, 0, 0)
self.horizontalLayout_9.setObjectName("horizontalLayout_9")
# Update Button
self.b2_update = QtWidgets.QPushButton(self.horizontalLayoutWidget_5)
self.b2_update.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.b2_update.setObjectName("b2_update")
self.horizontalLayout_9.addWidget(self.b2_update)
self.b2_update.clicked.connect(self.update_button)
# Remove Button
self.b3_remove = QtWidgets.QPushButton(self.horizontalLayoutWidget_5)
self.b3_remove.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.b3_remove.setObjectName("b3_remove")
self.horizontalLayout_9.addWidget(self.b3_remove)
# Exit Button
self.b4_exit = QtWidgets.QPushButton(self.horizontalLayoutWidget_5)
self.b4_exit.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.b4_exit.setObjectName("b4_exit")
self.horizontalLayout_9.addWidget(self.b4_exit)
self.b4_exit.clicked.connect(self.exit_popup_message)
User_Info.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(User_Info)
self.statusbar.setObjectName("statusbar")
User_Info.setStatusBar(self.statusbar)
self.retranslateUi(User_Info)
QtCore.QMetaObject.connectSlotsByName(User_Info)
def retranslateUi(self, User_Info):
_translate = QtCore.QCoreApplication.translate
User_Info.setWindowTitle(_translate("User_Info", "User Information"))
self.id_label.setText(_translate("User_Info", "ID Number:"))
self.id_output.setText(_translate("User_Info", "- - - - - - - - - -"))
self.Ph_label.setText(_translate("User_Info", "Phone Number:"))
self.Ph_output.setText(_translate("User_Info", "- - - - - - - - - - "))
self.name_label.setText(_translate("User_Info", "Name:"))
self.name_output.setText(_translate("User_Info", "- - - - - - - - - - "))
self.SuName_label.setText(_translate("User_Info", "Surname:"))
self.SuName_output.setText(_translate("User_Info", "- - - - - - - - - - "))
self.G_label.setText(_translate("User_Info", "Gender:"))
self.G_output.setText(_translate("User_Info", "- - - - - - - - - - "))
self.DOB_label.setText(_translate("User_Info", "Date Of Birth:"))
self.DOB_output.setText(_translate("User_Info", "- - - - - - - - - - "))
self.regiDate_label.setText(_translate("User_Info", "Registration Date:"))
self.regiDate_output.setText(_translate("User_Info", "- - - - - - - - - - "))
self.PCR_label.setText(_translate("User_Info", "PCR History:"))
self.b1_add.setText(_translate("User_Info", "Add PCR Record"))
item = self.PCR_Table.horizontalHeaderItem(0)
item.setText(_translate("User_Info", "Test Date"))
item = self.PCR_Table.horizontalHeaderItem(1)
item.setText(_translate("User_Info", "Result"))
self.b2_update.setText(_translate("User_Info", "Update User"))
self.b3_remove.setText(_translate("User_Info", "Remove User"))
self.b4_exit.setText(_translate("User_Info", "Exit"))
self.id_output.setText("1603010021")
self.Ph_output.setText("+905428769636")
self.name_output.setText("Osama")
self.SuName_output.setText("Abdelgawad")
self.G_output.setText("Male")
self.DOB_output.setText("1996-17-05")
self.regiDate_output.setText("2021-04-09")
def exit_popup_message(self):
msg = QMessageBox()
msg.setWindowTitle("Warning")
msg.setText("Are you sure you want to exit?")
msg.setIcon(QMessageBox.Question)
msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
x = msg.exec_()
if x == msg.Yes:
User_Info.close()
def update_button (self):
self.window = QtWidgets.QMainWindow()
self.ui = Ui_UpdatePage ()
self.ui.setupUi(self.window)
self.window.show()
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
User_Info = QtWidgets.QMainWindow()
ui = Ui_User_Info()
ui.setupUi(User_Info)
User_Info.show()
sys.exit(app.exec_())
Whenever in doubt, I suggest you to try to run your programs from a terminal/prompt, as IDEs have the tendency of hiding the full traceback of errors.
In this case, it will be the following:
Traceback (most recent call last):
File "/tmp/update_window.py", line 250, in exit_popup_message
UpdatePage.close()
NameError: name 'UpdatePage' is not defined
This is caused by two problems, one strictly programmatical, the other being conceptual.
When you run the update_window.py file, the block in the if __name__ statement is executed (because __name__ is '__main__') and since UpdatePage then exists, it works without problems. Note that UpdatePage is a global, and globals should always be avoided.
When you run the user_info.py file, instead, only that file's if __name__ is executed, and the other one is ignored, then UpdatePage doesn't exist, raising the exception and resulting in a crash.
The other problem is related to the fact that you're editing a file generated with pyuic and, as the warning in the header of those files clearly states, those files should never be modified unless you really know what you're doing, and one of the many reasons for discouraging this (which is considered bad practice) is that it usually leads to misunderstandings about object structure, just like in your case. Those files are only intended to be imported, there are very few, rare and specific cases for which modifying them could be considered, but the general rule is that if you know what you're doing, you will not do it.
Any implementation for a pyuic built UI should be done by subclassing its corresponding QWidget (QMainWindow, in your case) and using the generated UI class to build the ui on top of that. Not only this simplifies and clarifies things, but it also allows to properly access the instance methods, such as close(), instead of trying to do things in the wrong way (like accessing a global). I'll not go too deep into how all of this work, but the concept is that using your approach, the self in all those methods refers to an instance of Ui_UpdatePage, while in the correct approach it refers to the actual main window object.
So, in short, regenerate again your ui files with pyuic (in the following excerpt I generated the files update_ui.py and user_ui.py, and then implement the methods to the correct subclass:
update_window.py:
from PyQt5 import QtCore, QtGui, QtWidgets
from update_ui import Ui_UpdatePage
class UpdatePage(QtWidgets.QMainWindow, Ui_UpdatePage):
def __init__(self):
super().__init__()
self.setupUi(self)
def save_data (self):
# ...
def exit_popup_message (self):
# ...
if x == msg.Yes:
self.close()
user_info.py:
from PyQt5 import QtCore, QtGui, QtWidgets
from update_window import UpdatePage
from user_ui import Ui_User_Info
class UserInfo(QtWidgets.QMainWindow, Ui_User_Info):
def __init__(self):
super().__init__()
self.setupUi(self)
def exit_popup_message(self):
# ...
if x == msg.Yes:
self.close()
def update_button(self):
self.window = UpdatePage()
self.window.show()
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
userInfo = UserInfo()
userInfo.show()
sys.exit(app.exec_())
To know more on the above usage, read the official guidelines about using Designer.

How to close a window in Pyqt5 [duplicate]

This question already has answers here:
QtDesigner changes will be lost after redesign User Interface
(2 answers)
How to close a QDialog
(4 answers)
Closed 1 year ago.
I've created a program that allows you to login and sign up. When you have the right credentials it opens a window but it doesn't close. The same thing happens when you press the button to sign up. I've tried to use the close method but it doesn't work i always get:
AttributeError: type object 'Ui_Dialog' has no attribute 'close'
here is the full code of all the windows:
Login Page
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5 import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtWidgets import QMessageBox
import sqlite3
from welcome import Ui_MainWindow
from signup_page import Ui_Dialog2
import sys
#widget.setCurrentIndex(widget.currentIndex)
class Ui_Dialog(object):
def showMessageBox(self):
font = QtGui.QFont()
font.setPointSize(20)
self.label.setFont(font)
self.label.setStyleSheet("color: rgb(0, 0, 0);\n"
"background-color: rgb(255, 0, 0);")
self.label.setObjectName("label")
self.label.setText("WRONG USERNAME/PASSWORD")
def loginCheck(self):
username = self.username_input.text()
password = self.password_input.text()
connection = sqlite3.connect("login.db")
result = connection.execute("SELECT * FROM USERS WHERE USERNAME = ? AND PASSWORD = ?", (username, password))
if (len(result.fetchall())) > 0:
self.welcomewindow = QtWidgets.QMainWindow()
self.ui = Ui_MainWindow()
self.ui.setupUi(self.welcomewindow)
self.welcomewindow.show()
else:
self.showMessageBox()
def singup(self):
self.signup_page = QtWidgets.QDialog()
self.ui = Ui_Dialog2()
self.ui.setupUi(self.signup_page)
self.signup_page.show()
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(591, 457)
self.user_name_label = QtWidgets.QLabel(Dialog)
self.user_name_label.setGeometry(QtCore.QRect(190, 150, 81, 16))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.user_name_label.sizePolicy().hasHeightForWidth())
self.user_name_label.setSizePolicy(sizePolicy)
self.user_name_label.setSizeIncrement(QtCore.QSize(0, 0))
self.user_name_label.setBaseSize(QtCore.QSize(0, 0))
font = QtGui.QFont()
font.setPointSize(13)
self.user_name_label.setFont(font)
self.user_name_label.setObjectName("user_name_label")
self.password_label = QtWidgets.QLabel(Dialog)
self.password_label.setGeometry(QtCore.QRect(190, 210, 81, 16))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.password_label.sizePolicy().hasHeightForWidth())
self.password_label.setSizePolicy(sizePolicy)
self.password_label.setSizeIncrement(QtCore.QSize(0, 0))
self.password_label.setBaseSize(QtCore.QSize(0, 0))
font = QtGui.QFont()
font.setPointSize(13)
self.password_label.setFont(font)
self.password_label.setObjectName("password_label")
self.username_input = QtWidgets.QLineEdit(Dialog)
self.username_input.setGeometry(QtCore.QRect(280, 150, 141, 20))
self.username_input.setObjectName("username_input")
self.password_input = QtWidgets.QLineEdit(Dialog)
self.password_input.setGeometry(QtCore.QRect(280, 210, 141, 20))
self.password_input.setObjectName("password_input")
self.password_input.setEchoMode(self.password_input.Password)
self.login_btn = QtWidgets.QPushButton(Dialog)
self.login_btn.setGeometry(QtCore.QRect(200, 260, 81, 31))
font = QtGui.QFont()
font.setPointSize(13)
self.login_btn.setFont(font)
self.login_btn.setObjectName("login_btn")
#########Button Event##########
self.login_btn.clicked.connect(self.loginCheck)
###############################
self.signup_btn = QtWidgets.QPushButton(Dialog)
self.signup_btn.setGeometry(QtCore.QRect(300, 260, 81, 31))
########Button Event##########
self.signup_btn.clicked.connect(self.singup)
##############################
font = QtGui.QFont()
font.setPointSize(13)
self.signup_btn.setFont(font)
self.signup_btn.setObjectName("signup_btn")
self.login_title = QtWidgets.QLabel(Dialog)
self.login_title.setGeometry(QtCore.QRect(240, 40, 91, 71))
font = QtGui.QFont()
font.setPointSize(20)
self.login_title.setFont(font)
self.login_title.setObjectName("login_title")
self.label = QtWidgets.QLabel(Dialog)
self.label.setGeometry(QtCore.QRect(130, 370, 391, 31))
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Login Page"))
self.user_name_label.setText(_translate("Dialog", "Username"))
self.password_label.setText(_translate("Dialog", "Password"))
self.login_btn.setText(_translate("Dialog", "Login"))
self.signup_btn.setText(_translate("Dialog", "Sign Up"))
self.login_title.setText(_translate("Dialog", " Login"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
widget = QtWidgets.QStackedWidget()
MainWindow = QtWidgets.QMainWindow()
ui = Ui_Dialog()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
The main window:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(593, 458)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(200, 180, 221, 71))
font = QtGui.QFont()
font.setPointSize(40)
self.label.setFont(font)
self.label.setObjectName("label")
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.label.setText(_translate("MainWindow", "Welcome"))
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_())
and the signup page:
from PyQt5 import QtCore, QtGui, QtWidgets
import sqlite3
from welcome import Ui_MainWindow
import re
from PyQt5.QtWidgets import QMessageBox
class Ui_Dialog2(object):
def showMessageBox_password(self):
font = QtGui.QFont()
font.setPointSize(20)
self.label.setFont(font)
self.label.setStyleSheet("color: rgb(0, 0, 0);\n"
"background-color: rgb(255, 0, 0);")
self.label.setObjectName("label")
self.label.setText("INVALID PASSWORD")
def showMessageBox_email(self):
font = QtGui.QFont()
font.setPointSize(20)
self.label.setFont(font)
self.label.setStyleSheet("color: rgb(0, 0, 0);\n"
"background-color: rgb(255, 0, 0);")
self.label.setObjectName("label")
self.label.setText(" INVALID EMAIL")
def insertData(self):
username = self.username_entry.text()
password = self.password_entry.text()
email = self.email_entry.text()
connection = sqlite3.connect("login.db")
regex = '^(\w|\.|\_|\-)+[#](\w|\_|\-|\.)+[.]\w{2,3}$'
valid_email = True
valid_password = True
if(re.search(regex, email)):
valid_email = True
else:
valid_email = False
if len(password) > 7:
valid_password = True
else:
valid_password = False
if valid_email == True and valid_password == True:
connection.execute("INSERT INTO USERS VALUES(?,?,?)", (username, email, password))
connection.commit()
self.welcomewindow = QtWidgets.QMainWindow()
self.ui = Ui_MainWindow()
self.ui.setupUi(self.welcomewindow)
self.welcomewindow.show()
if valid_email == False:
self.showMessageBox_email()
elif valid_password == False:
self.showMessageBox_password()
connection.close()
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(593, 458)
self.user_name_label = QtWidgets.QLabel(Dialog)
self.user_name_label.setGeometry(QtCore.QRect(190, 200, 81, 16))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.user_name_label.sizePolicy().hasHeightForWidth())
self.user_name_label.setSizePolicy(sizePolicy)
self.user_name_label.setSizeIncrement(QtCore.QSize(0, 0))
self.user_name_label.setBaseSize(QtCore.QSize(0, 0))
font = QtGui.QFont()
font.setPointSize(13)
self.user_name_label.setFont(font)
self.user_name_label.setObjectName("user_name_label")
self.password_label = QtWidgets.QLabel(Dialog)
self.password_label.setGeometry(QtCore.QRect(190, 240, 81, 16))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.password_label.sizePolicy().hasHeightForWidth())
self.password_label.setSizePolicy(sizePolicy)
self.password_label.setSizeIncrement(QtCore.QSize(0, 0))
self.password_label.setBaseSize(QtCore.QSize(0, 0))
font = QtGui.QFont()
font.setPointSize(13)
self.password_label.setFont(font)
self.password_label.setObjectName("password_label")
self.email_label = QtWidgets.QLabel(Dialog)
self.email_label.setGeometry(QtCore.QRect(190, 160, 81, 16))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.email_label.sizePolicy().hasHeightForWidth())
self.email_label.setSizePolicy(sizePolicy)
self.email_label.setSizeIncrement(QtCore.QSize(0, 0))
self.email_label.setBaseSize(QtCore.QSize(0, 0))
font = QtGui.QFont()
font.setPointSize(13)
self.email_label.setFont(font)
self.email_label.setObjectName("email_label")
self.email_entry = QtWidgets.QLineEdit(Dialog)
self.email_entry.setGeometry(QtCore.QRect(270, 160, 200, 20))
self.email_entry.setObjectName("email_entry")
self.username_entry = QtWidgets.QLineEdit(Dialog)
self.username_entry.setGeometry(QtCore.QRect(270, 200, 200, 20))
self.username_entry.setObjectName("username_entry")
self.password_entry = QtWidgets.QLineEdit(Dialog)
self.password_entry.setGeometry(QtCore.QRect(270, 240, 200, 20))
self.password_entry.setObjectName("password_entry")
self.password_entry.setEchoMode(self.password_entry.Password)
self.sign_up_button = QtWidgets.QPushButton(Dialog)
self.sign_up_button.setGeometry(QtCore.QRect(270, 280, 81, 31))
font = QtGui.QFont()
font.setPointSize(13)
self.sign_up_button.setFont(font)
self.sign_up_button.setObjectName("sign_up_button")
self.sign_up_button.clicked.connect(self.insertData)
self.login_title = QtWidgets.QLabel(Dialog)
self.login_title.setGeometry(QtCore.QRect(220, 50, 191, 71))
font = QtGui.QFont()
font.setPointSize(20)
self.login_title.setFont(font)
self.login_title.setObjectName("login_title")
self.label = QtWidgets.QLabel(Dialog)
self.label.setGeometry(QtCore.QRect(170, 360, 251, 31))
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Sign Up Page"))
self.user_name_label.setText(_translate("Dialog", "Username"))
self.password_label.setText(_translate("Dialog", "Password"))
self.email_label.setText(_translate("Dialog", "Email"))
self.sign_up_button.setText(_translate("Dialog", "Sign Up"))
self.login_title.setText(_translate("Dialog", "Create Account"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_Dialog2()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())

QObject::setParent: Cannot set parent, new parent is in a different thread in Python

I am facing a problem with the GUI I developed using PyQt5.
The app tries to update the value of a progress bar of the window from a different thread (QThreadPool()). When it tries to update the progress bar, the python gives a warning as below:
QObject::setParent: Cannot set parent, new parent is in a different thread
This doesn't affect the app to certain extent but after a while the app crashes with the following error message.
QBackingStore::endPaint() called with active painter on backingstore paint device
Could anyone help me to get rid of the first warning? I guess that will solve the problem.
I will post a minimal example of the code.
main.py
import sys
from PyQt5.QtCore import *
from PyQt5 import QtCore, QtGui, QtWidgets
import thread_for_audio_record
import time
class FW(object):
def __init__(self):
self.threadpool = QThreadPool()
def f_w(self, window):
self.window = window
self.window.setObjectName("Test")
self.window.resize(1054, 700)
self.window.setStyleSheet("background-color: rgb(180, 180, 180);")
self.central_widget = QtWidgets.QWidget(self.window)
self.central_widget.setObjectName("centralwidget")
self.horizontal_layout = QtWidgets.QHBoxLayout(self.central_widget)
self.horizontal_layout.setObjectName("horizontalLayout")
spacer_item = QtWidgets.QSpacerItem(129, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontal_layout.addItem(spacer_item)
self.vertical_layout = QtWidgets.QVBoxLayout()
self.vertical_layout.setObjectName("verticalLayout")
spacer_item_1 = QtWidgets.QSpacerItem(128, 13, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.vertical_layout.addItem(spacer_item_1)
self.label_utterance = QtWidgets.QLabel(self.central_widget)
font = QtGui.QFont()
font.setPointSize(15)
font.setBold(True)
font.setBold(True)
font.setWeight(75)
self.label_utterance.setFont(font)
self.label_utterance.setAlignment(QtCore.Qt.AlignCenter)
self.label_utterance.setObjectName("label_utterance")
self.vertical_layout.addWidget(self.label_utterance)
self.text_edit_utterance = QtWidgets.QTextEdit(self.central_widget)
self.text_edit_utterance.setStyleSheet("background-color: rgb(255, 255, 255);")
self.text_edit_utterance.setObjectName("text_edit_utterance")
self.text_edit_utterance.setReadOnly(True)
self.text_edit_utterance.setFont(font)
self.vertical_layout.addWidget(self.text_edit_utterance)
self.line_edit_message_for_user = QtWidgets.QLineEdit(self.central_widget)
self.line_edit_message_for_user.setStyleSheet("background-color: rgb(255, 255, 255);")
self.line_edit_message_for_user.setObjectName("lineEdit")
self.progressBar = QtWidgets.QProgressBar(self.central_widget)
self.progressBar.setProperty("value", 0)
self.progressBar.setObjectName("progressBar")
self.vertical_layout.addWidget(self.progressBar)
self.vertical_layout.addWidget(self.line_edit_message_for_user)
self.push_button_start_recording = QtWidgets.QPushButton(self.central_widget)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.push_button_start_recording.setFont(font)
self.push_button_start_recording.setStyleSheet("background-color: rgb(85, 170, 0);")
self.push_button_start_recording.setObjectName("pushButton_start_
recording")
self.push_button_start_recording.clicked.connect(self.start_button_
func)
self.vertical_layout.addWidget(self.push_button_start_recording)
self.push_button_end_recording = QtWidgets.QPushButton(self.central_widget)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.push_button_end_recording.setFont(font)
self.push_button_end_recording.setStyleSheet("background-color: rgb(182, 0, 0);")
self.push_button_end_recording.setObjectName("pushButton_end_
recording")
self.vertical_layout.addWidget(self.push_button_end_recording)
self.label_status = QtWidgets.QLabel(self.central_widget)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_status.setFont(font)
self.label_status.setObjectName("label_status")
self.vertical_layout.addWidget(self.label_status)
self.text_edit_status = QtWidgets.QTextEdit(self.central_widget)
self.text_edit_status.setStyleSheet("background-color: rgb(255, 255, 255);")
self.text_edit_status.setObjectName("textEdit_status")
self.text_edit_status.setReadOnly(True)
self.vertical_layout.addWidget(self.text_edit_status)
self.push_button_record_again = QtWidgets.QPushButton(self.central_widget)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.push_button_record_again.setFont(font)
self.push_button_record_again.setStyleSheet("background-color: rgb(255, 255, 127);")
self.push_button_record_again.setObjectName("pushButton_record_
again")
self.vertical_layout.addWidget(self.push_button_record_again)
self.push_button_next_utterance = QtWidgets.QPushButton(self.central_widget)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.push_button_next_utterance.setFont(font)
self.push_button_next_utterance.setStyleSheet("background-color: rgb(85, 170, 0);")
self.push_button_next_utterance.setObjectName("pushButton_next_
utterance")
self.vertical_layout.addWidget(self.push_button_next_utterance)
spacer_item_2 = QtWidgets.QSpacerItem(128, 13, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.vertical_layout.addItem(spacer_item_2)
self.horizontal_layout.addLayout(self.vertical_layout)
spacer_item_3 = QtWidgets.QSpacerItem(128, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontal_layout.addItem(spacer_item_3)
self.window.setCentralWidget(self.central_widget)
self.menubar = QtWidgets.QMenuBar(self.window)
self.menubar.setGeometry(QtCore.QRect(0, 0, 1054, 21))
self.menubar.setObjectName("menubar")
self.window.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(self.window)
self.statusbar.setObjectName("statusbar")
self.window.setStatusBar(self.statusbar)
self.retranslate_ui(self.window)
QtCore.QMetaObject.connectSlotsByName(self.window)
def retranslate_ui(self, window):
_translate = QtCore.QCoreApplication.translate
window.setWindowTitle(_translate("Utterance Recording", "Test"))
self.label_utterance.setText(_translate("Utterance Recording", "Test"))
self.line_edit_message_for_user.setText(_translate("Utterance Recording", "Test."))
self.text_edit_utterance.setText(_translate("utterance_parsing", ('Test')))
self.push_button_start_recording.setText(_translate("Utterance Recording", "Start Recording"))
self.push_button_end_recording.setText(_translate("Utterance Recording", "End Recording"))
self.label_status.setText(_translate("Utterance Recording", "Test"))
self.push_button_record_again.setText(_translate("Utterance Recording", "Test"))
self.push_button_next_utterance.setText(_translate("Utterance Recording", "Test"))
def inside_thread(self):
percentage = 0
while percentage < 120:
percentage = percentage + 20
time.sleep(0.2)
self.progressBar.setValue(percentage)
def start_button_func(self):
self.worker = thread_for_audio_record.Worker(self.inside_thread)
self.threadpool.start(self.worker)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
utterance_parsing_window = QtWidgets.QMainWindow()
utterance_parsing = FW()
utterance_parsing.f_w(utterance_parsing_window)
utterance_parsing_window.show()
sys.exit(app.exec_())
thread_for_audio_record.py
import os
from PyQt5.QtCore import *
class Worker(QRunnable):
def __init__(self, fn):
super(Worker, self).__init__()
self.fn = fn
self.originating_PID = os.getpid()
self._running = True
#pyqtSlot()
def run(self):
self.fn()
Click the Start Recording button and you will see the progress bar getting updated. But the warning message is given cause the update is from a different thread.
First, do not modify the code generated by Qt Designer as PyQt recommends, instead create another class that inherits from the appropriate widget and use the initial class as an interface.
Going to the point, Qt does not allow the GUI to be updated from another thread directly, in your case the setValue of the QProgressBar is called in the secondary thread causing the painting to be made in the secuandario thread so Qt complains that it is not guaranteed operation (for example in your case it does not generate problems apparently but Qt does not guarantee that this always happens). The update of the GUI from other threads must be indirectly, which can be through signals, QEvent, QMetaObject::invokeMethod, etc. In this case I will use the signals:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
import thread_for_audio_record
import time
class FW(object):
def f_w(self, window):
self.window = window
self.window.setObjectName("Test")
self.window.resize(1054, 700)
self.window.setStyleSheet("background-color: rgb(180, 180, 180);")
self.central_widget = QtWidgets.QWidget(self.window)
self.central_widget.setObjectName("centralwidget")
self.horizontal_layout = QtWidgets.QHBoxLayout(self.central_widget)
self.horizontal_layout.setObjectName("horizontalLayout")
spacer_item = QtWidgets.QSpacerItem(129, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontal_layout.addItem(spacer_item)
self.vertical_layout = QtWidgets.QVBoxLayout()
self.vertical_layout.setObjectName("verticalLayout")
spacer_item_1 = QtWidgets.QSpacerItem(128, 13, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.vertical_layout.addItem(spacer_item_1)
self.label_utterance = QtWidgets.QLabel(self.central_widget)
font = QtGui.QFont()
font.setPointSize(15)
font.setBold(True)
font.setBold(True)
font.setWeight(75)
self.label_utterance.setFont(font)
self.label_utterance.setAlignment(QtCore.Qt.AlignCenter)
self.label_utterance.setObjectName("label_utterance")
self.vertical_layout.addWidget(self.label_utterance)
self.text_edit_utterance = QtWidgets.QTextEdit(self.central_widget)
self.text_edit_utterance.setStyleSheet("background-color: rgb(255, 255, 255);")
self.text_edit_utterance.setObjectName("text_edit_utterance")
self.text_edit_utterance.setReadOnly(True)
self.text_edit_utterance.setFont(font)
self.vertical_layout.addWidget(self.text_edit_utterance)
self.line_edit_message_for_user = QtWidgets.QLineEdit(self.central_widget)
self.line_edit_message_for_user.setStyleSheet("background-color: rgb(255, 255, 255);")
self.line_edit_message_for_user.setObjectName("lineEdit")
self.progressBar = QtWidgets.QProgressBar(self.central_widget)
self.progressBar.setProperty("value", 0)
self.progressBar.setObjectName("progressBar")
self.vertical_layout.addWidget(self.progressBar)
self.vertical_layout.addWidget(self.line_edit_message_for_user)
self.push_button_start_recording = QtWidgets.QPushButton(self.central_widget)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.push_button_start_recording.setFont(font)
self.push_button_start_recording.setStyleSheet("background-color: rgb(85, 170, 0);")
self.push_button_start_recording.setObjectName("pushButton_start_ recording")
self.vertical_layout.addWidget(self.push_button_start_recording)
self.push_button_end_recording = QtWidgets.QPushButton(self.central_widget)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.push_button_end_recording.setFont(font)
self.push_button_end_recording.setStyleSheet("background-color: rgb(182, 0, 0);")
self.push_button_end_recording.setObjectName("pushButton_end_recording")
self.vertical_layout.addWidget(self.push_button_end_recording)
self.label_status = QtWidgets.QLabel(self.central_widget)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_status.setFont(font)
self.label_status.setObjectName("label_status")
self.vertical_layout.addWidget(self.label_status)
self.text_edit_status = QtWidgets.QTextEdit(self.central_widget)
self.text_edit_status.setStyleSheet("background-color: rgb(255, 255, 255);")
self.text_edit_status.setObjectName("textEdit_status")
self.text_edit_status.setReadOnly(True)
self.vertical_layout.addWidget(self.text_edit_status)
self.push_button_record_again = QtWidgets.QPushButton(self.central_widget)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.push_button_record_again.setFont(font)
self.push_button_record_again.setStyleSheet("background-color: rgb(255, 255, 127);")
self.push_button_record_again.setObjectName("pushButton_record_again")
self.vertical_layout.addWidget(self.push_button_record_again)
self.push_button_next_utterance = QtWidgets.QPushButton(self.central_widget)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.push_button_next_utterance.setFont(font)
self.push_button_next_utterance.setStyleSheet("background-color: rgb(85, 170, 0);")
self.push_button_next_utterance.setObjectName("pushButton_next_utterance")
self.vertical_layout.addWidget(self.push_button_next_utterance)
spacer_item_2 = QtWidgets.QSpacerItem(128, 13, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.vertical_layout.addItem(spacer_item_2)
self.horizontal_layout.addLayout(self.vertical_layout)
spacer_item_3 = QtWidgets.QSpacerItem(128, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontal_layout.addItem(spacer_item_3)
self.window.setCentralWidget(self.central_widget)
self.menubar = QtWidgets.QMenuBar(self.window)
self.menubar.setGeometry(QtCore.QRect(0, 0, 1054, 21))
self.menubar.setObjectName("menubar")
self.window.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(self.window)
self.statusbar.setObjectName("statusbar")
self.window.setStatusBar(self.statusbar)
self.retranslate_ui(self.window)
QtCore.QMetaObject.connectSlotsByName(self.window)
def retranslate_ui(self, window):
_translate = QtCore.QCoreApplication.translate
window.setWindowTitle(_translate("Utterance Recording", "Altran Audio Manager"))
self.label_utterance.setText(_translate("Utterance Recording", "Test"))
self.line_edit_message_for_user.setText(_translate("Utterance Recording", "Test."))
self.text_edit_utterance.setText(_translate("utterance_parsing", ('Test')))
self.push_button_start_recording.setText(_translate("Utterance Recording", "Start Recording"))
self.push_button_end_recording.setText(_translate("Utterance Recording", "End Recording"))
self.label_status.setText(_translate("Utterance Recording", "Test"))
self.push_button_record_again.setText(_translate("Utterance Recording", "Test"))
self.push_button_next_utterance.setText(_translate("Utterance Recording", "Test"))
class MainWindow(QtWidgets.QMainWindow, FW):
progressChanged = QtCore.pyqtSignal(int)
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.threadpool = QtCore.QThreadPool()
self.f_w(self)
self.push_button_start_recording.clicked.connect(self.start_button_func)
self.progressChanged.connect(self.progressBar.setValue)
def inside_thread(self):
percentage = 0
while percentage < 120:
percentage = percentage + 20
time.sleep(0.2)
self.progressChanged.emit(percentage)
def start_button_func(self):
self.worker = thread_for_audio_record.Worker(self.inside_thread)
self.threadpool.start(self.worker)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())

Categories

Resources