as the missing method of QTabWidget of this code is written? - python

import sys,random
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow,QDialog
class Ui_TabWidget(object):
def setupUi(self, TabWidget):
TabWidget.setObjectName("TabWidget")
TabWidget.resize(264, 113)
self.PILA = QtWidgets.QWidget()
self.PILA.setObjectName("PILA")
self.LineMOSTRAR = QtWidgets.QLineEdit(self.PILA)
self.LineMOSTRAR.setGeometry(QtCore.QRect(10, 50, 231, 21))
self.LineMOSTRAR.setObjectName("LineMOSTRAR")
self.BtnINSERTA = QtWidgets.QPushButton(self.PILA)
self.BtnINSERTA.setGeometry(QtCore.QRect(10, 10, 75, 23))
self.BtnINSERTA.setObjectName("BtnINSERTA")
self.BtnSALIR = QtWidgets.QPushButton(self.PILA)
self.BtnSALIR.setGeometry(QtCore.QRect(170, 10, 75, 23))
self.BtnSALIR.setObjectName("BtnSALIR")
self.BtnELIMINA = QtWidgets.QPushButton(self.PILA)
self.BtnELIMINA.setGeometry(QtCore.QRect(90, 10, 75, 23))
self.BtnELIMINA.setObjectName("BtnELIMINA")
my error according python is in TabWidget.addTab
TabWidget.addTab(self.PILA, "") #This is mi error according pyqt5
self.COLA = QtWidgets.QWidget()
self.COLA.setObjectName("COLA")
self.BtnINSERTA_2 = QtWidgets.QPushButton(self.COLA)
self.BtnINSERTA_2.setGeometry(QtCore.QRect(10, 10, 75, 23))
self.BtnINSERTA_2.setObjectName("BtnINSERTA_2")
self.BtnELIMINA_2 = QtWidgets.QPushButton(self.COLA)
self.BtnELIMINA_2.setGeometry(QtCore.QRect(90, 10, 75, 23))
self.BtnELIMINA_2.setObjectName("BtnELIMINA_2")
self.BtnSALIR_2 = QtWidgets.QPushButton(self.COLA)
self.BtnSALIR_2.setGeometry(QtCore.QRect(170, 10, 75, 23))
self.BtnSALIR_2.setObjectName("BtnSALIR_2")
self.LineMOSTRAR_2 = QtWidgets.QLineEdit(self.COLA)
self.LineMOSTRAR_2.setGeometry(QtCore.QRect(10, 50, 231, 21))
self.LineMOSTRAR_2.setObjectName("LineMOSTRAR_2")
TabWidget.addTab(self.COLA, "")
self.COLA_C = QtWidgets.QWidget()
self.COLA_C.setObjectName("COLA_C")
self.BtnINSERTA_3 = QtWidgets.QPushButton(self.COLA_C)
self.BtnINSERTA_3.setGeometry(QtCore.QRect(10, 10, 75, 23))
self.BtnINSERTA_3.setObjectName("BtnINSERTA_3")
self.BtnELIMINA_3 = QtWidgets.QPushButton(self.COLA_C)
self.BtnELIMINA_3.setGeometry(QtCore.QRect(90, 10, 75, 23))
self.BtnELIMINA_3.setObjectName("BtnELIMINA_3")
self.BtnSALIR_3 = QtWidgets.QPushButton(self.COLA_C)
self.BtnSALIR_3.setGeometry(QtCore.QRect(170, 10, 75, 23))
self.BtnSALIR_3.setObjectName("BtnSALIR_3")
self.LineMOSTRAR_3 = QtWidgets.QLineEdit(self.COLA_C)
self.LineMOSTRAR_3.setGeometry(QtCore.QRect(10, 50, 231, 21))
self.LineMOSTRAR_3.setObjectName("LineMOSTRAR_3")
TabWidget.addTab(self.COLA_C, "")
#WIDGET Btn
#Btn for 1st tab of mi app
self.BtnINSERTA.clicked.connect(self.INSERTA)
self.BtnELIMINA.clicked.connect(self.ELIMINA)
self.BtnSALIR.clicked.connect(self.SALIR)
#Btn for 2nd tab of mi app
self.BtnINSERTA.clicked.connect(self.INSERTA_2)
self.BtnELIMINA.clicked.connect(self.ELIMINA_2)
self.BtnSALIR.clicked.connect(self.SALIR_2)
#Btn for 3rd tab of mi app
self.BtnINSERTA.clicked.connect(self.INSERTA_3)
self.BtnELIMINA.clicked.connect(self.ELIMINA_3)
self.BtnSALIR.clicked.connect(self.SALIR_3)
self.retranslateUi(TabWidget)
TabWidget.setCurrentIndex(0)
QtCore.QMetaObject.connectSlotsByName(TabWidget)
#Method for my btns
def INSERTA(self):
self.LineMOSTRAR.setText('PILA LLENA - DESBORDAMIENTO')
def ELIMINA(self):
self.LineMOSTRAR.setText('PILA VACIA-SUBDESBORDAMIENTO')
def SALIR(self):
exit()
def SALIR_2(self):#RESET Btn
def INSERTA_2(self):
def ELIMINA_2(self):
def INSERTA_3(self):
def ELIMINA_3(self):
def SALIR_3 (self):
exit()
#end of the method
def retranslateUi(self, TabWidget):
_translate = QtCore.QCoreApplication.translate
TabWidget.setWindowTitle(_translate("TabWidget", "TabWidget"))
self.BtnINSERTA.setText(_translate("TabWidget", "Insertar"))
self.BtnSALIR.setText(_translate("TabWidget", "SALIR"))
self.BtnELIMINA.setText(_translate("TabWidget", "Eliminar"))
TabWidget.setTabText(TabWidget.indexOf(self.PILA), _translate("TabWidget", "Tab 1"))
self.BtnINSERTA_2.setText(_translate("TabWidget", "Insertar"))
self.BtnELIMINA_2.setText(_translate("TabWidget", "Eliminar"))
self.BtnSALIR_2.setText(_translate("TabWidget", "RESET"))
TabWidget.setTabText(TabWidget.indexOf(self.COLA), _translate("TabWidget", "Tab 2"))
self.BtnINSERTA_3.setText(_translate("TabWidget", "Insertar"))
self.BtnELIMINA_3.setText(_translate("TabWidget", "Eliminar"))
self.BtnSALIR_3.setText(_translate("TabWidget", "SALIR"))
TabWidget.setTabText(TabWidget.indexOf(self.COLA_C), _translate("TabWidget", "Page"))
#Qwidget Call
app = QApplication(sys.argv)
window = QDialog()
ui = Ui_TabWidget()
ui.setupUi(window)
window.show()
sys.exit(app.exec_())
And this is my error ui.setupUi(window)
How i can fix //AttributeError: 'QDialog' object has no attribute 'addTab'
when he tried to run the code gives me errors on both lines so I can not think of anything new and do not understand that I have read many explanations

Your setupUi method is expecting a QTabWidget, but your code is passing it a QDialog. While I don't have a PyQt5 environment currently set up to test against, you should be able to simply replace your window = QDialog with a window = QTabWidget() below #Qwidget Call.

Related

interacting with buttons in QDialog do not work when launched from a MainWindow in pyqt6

I have been struggling to solve this problem within my pyqt program, I am making a program where the user can use their controllers as a mouse in python. However I am stuck in this part where the user can map individual controls with their corresponding keys window. To be more specific, whenever I launch this Dialog: "controllerMapping.py" in my mainWindow/app, any buttons and interactions with the dialog do not work. However when run "controllerMapping.py" directly as a standalone window, everything seems to work?
Here's the code for the MainWindow invokking controllerMapping.py:
def summon_controllerMapping(self):
# TODO: UNRESPONSIVE AS HELL
self.cm = QtWidgets.QDialog()
ui = controllerMapping.Ui_Dialog()
ui.setupUi(self.cm)
self.cm.show()
And here's the entire code for controllerMapping.py, I used the pyqt-designer to create the widget then added my own methods to hook for the buttons.
from PyQt6 import QtCore, QtGui, QtWidgets
import editMapping
import init_db
import mapping
preset_columns = init_db.get_table_columns("presets")
controls_columns = init_db.get_table_columns("mapping")
keybind_data = init_db.get_table_data("mapping")
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(500, 500)
self.buttonBox = QtWidgets.QDialogButtonBox(Dialog)
self.buttonBox.setGeometry(QtCore.QRect(130, 440, 341, 32))
self.buttonBox.setOrientation(QtCore.Qt.Orientation.Horizontal)
self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.StandardButton.Cancel|QtWidgets.QDialogButtonBox.StandardButton.Ok)
self.buttonBox.setObjectName("buttonBox")
self.desc_lbl = QtWidgets.QLabel(Dialog)
self.desc_lbl.setGeometry(QtCore.QRect(30, 30, 431, 16))
self.desc_lbl.setObjectName("desc_lbl")
self.mapping_table = QtWidgets.QTableWidget(Dialog)
self.mapping_table.setGeometry(QtCore.QRect(30, 70, 441, 291))
self.mapping_table.setObjectName("mapping_table")
self.mapping_table.setColumnCount(0)
self.mapping_table.setRowCount(0)
self.edit_btn = QtWidgets.QPushButton(Dialog)
self.edit_btn.setGeometry(QtCore.QRect(390, 360, 81, 24))
self.edit_btn.setObjectName("edit_btn")
self.selected_preset_lbl = QtWidgets.QLabel(Dialog)
self.selected_preset_lbl.setGeometry(QtCore.QRect(30, 400, 91, 21))
self.selected_preset_lbl.setObjectName("selected_preset_lbl")
self.presets_list = QtWidgets.QComboBox(Dialog)
self.presets_list.setGeometry(QtCore.QRect(130, 400, 161, 22))
self.presets_list.setObjectName("presets_list")
self.refresh_btn = QtWidgets.QPushButton(Dialog)
self.refresh_btn.setGeometry(QtCore.QRect(30, 360, 81, 24))
self.refresh_btn.setObjectName("refresh_btn")
self.retranslateUi(Dialog)
self.buttonBox.accepted.connect(Dialog.accept) # type: ignore
self.buttonBox.rejected.connect(Dialog.reject) # type: ignore
QtCore.QMetaObject.connectSlotsByName(Dialog)
self.presets_list.setCurrentIndex(-1)
self.populate_mapping_table()
self.populate_presets_list()
self.bind_btn()
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.desc_lbl.setText(_translate("Dialog", "Map Controls: Here is a list of controller buttons and their respective mapping"))
self.edit_btn.setText(_translate("Dialog", "Edit"))
self.selected_preset_lbl.setText(_translate("Dialog", "Selected Preset:"))
self.refresh_btn.setText(_translate("Dialog", "Refresh"))
def bind_btn(self):
self.edit_btn.clicked.connect(self.summon_editMapping)
self.presets_list.currentTextChanged.connect(self.set_new_preset)
def summon_editMapping(self):
self.em = QtWidgets.QDialog()
ui = editMapping.Ui_Dialog()
ui.setupUi(self.em)
self.em.show()
def populate_mapping_table(self):
print("mapping table")
column_cnt = len(preset_columns) + 1
keybinds_cnt = len(controls_columns) + 1
self.mapping_table.setColumnCount(column_cnt)
self.mapping_table.setRowCount(keybinds_cnt)
self.mapping_table.setItem(0, 0, QtWidgets.QTableWidgetItem("CONTROLS"))
for column, preset in enumerate(preset_columns):
self.mapping_table.setItem(0, column+1, QtWidgets.QTableWidgetItem(preset))
for row, controller in enumerate(controls_columns):
self.mapping_table.setItem(row+1, 0, QtWidgets.QTableWidgetItem(controller))
for column, keybinds in enumerate(keybind_data):
for row, keybind in enumerate(keybinds):
self.mapping_table.setItem(row+1, column+1, QtWidgets.QTableWidgetItem(keybind))
def populate_presets_list(self):
print("presets")
for preset in preset_columns:
self.presets_list.addItem(preset)
def set_new_preset(self):
print("Hello world")
"""selected_preset = self.presets_list.currentText()
print(selected_preset)
db = "databases/controls.db"
conn = sqlite3.connect(db)
for column in init_db.get_table_columns("presets"):
init_db.update_data("presets", column, False)
init_db.update_data("presets", selected_preset, True)
r = init_db.get_table_data("presets")
print(r)
conn.close()"""
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Dialog = QtWidgets.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec())
I tried using putting print statements in the self.bind_btn() function, to no avail they did not work.
Every function except for self. Every method seems to be working fine except for self.bind_btn()

PyQt5 - closes application bec. of error with .value() method [duplicate]

This question already has an answer here:
Get text from qtextedit and assign it to a variable
(1 answer)
Closed 4 years ago.
whenever I click a button in the second window of my PyQt5 application that should just print the value of a QDateEdit in the GUI, it closes with the line: "Process finished with exit code -1073740791 (0xC0000409)". I figured out that the problem has something to do with the .value() method. Here's the Minimal to reproduce the bug with the Ui_Form class below:
import sys
from PyQt5 import QtWidgets
from ui.fenster import Ui_Form
app = QtWidgets.QApplication(sys.argv)
class AppendWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.ui = Ui_Form()
self.ui.setupUi(self)
self.ui.submit.clicked.connect(self.show_value)
def show_value(self):
print(self.ui.date.value())
append = AppendWindow()
append.show()
sys.exit(app.exec_())
Ui_Form:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(413, 215)
self.date = QtWidgets.QDateEdit(Form)
self.date.setGeometry(QtCore.QRect(72, 26, 321, 20))
self.date.setObjectName("date")
self.label = QtWidgets.QLabel(Form)
self.label.setGeometry(QtCore.QRect(9, 26, 57, 16))
self.label.setObjectName("label")
self.age = QtWidgets.QSpinBox(Form)
self.age.setGeometry(QtCore.QRect(70, 120, 321, 20))
self.age.setObjectName("age")
self.label_2 = QtWidgets.QLabel(Form)
self.label_2.setGeometry(QtCore.QRect(10, 120, 23, 16))
self.label_2.setObjectName("label_2")
self.label_3 = QtWidgets.QLabel(Form)
self.label_3.setGeometry(QtCore.QRect(9, 69, 27, 16))
self.label_3.setObjectName("label_3")
self.name = QtWidgets.QPlainTextEdit(Form)
self.name.setGeometry(QtCore.QRect(72, 69, 319, 21))
self.name.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.name.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.name.setObjectName("name")
self.submit = QtWidgets.QPushButton(Form)
self.submit.setGeometry(QtCore.QRect(170, 170, 75, 23))
self.submit.setObjectName("submit")
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.label.setText(_translate("Form", "Geburtsjahr"))
self.label_2.setText(_translate("Form", "Alter"))
self.label_3.setText(_translate("Form", "Name"))
self.submit.setText(_translate("Form", "Absenden!"))
Does anyone know how to fix this?
I appreciate your help!
You need to add app.exec() in your main code in order to start the main loop.
app = QtWidgets.QApplication(sys.argv)
app.exec()
The main loop handles all the incoming events and passes them to your GUI elements.

adding and removing widgets in PyQt

What I'm doing is about that when I clicked the date of the
calendar ,then it will display the class of UI_tab which is a tabwidget ,including two tabs.each tab includes some labels and others.However it
cant't work.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Tab(object):
# create tabwidget
def __init__(self,parentw,*args):
print(args)
print(parentw)
super().__init__()
self.font = QtGui.QFont()
self.font.setFamily("仿宋")
self.font.setPointSize(10)
self.font.setItalic(False)
self.font.setUnderline(False)
self.w=['title0','title1',
'creator0','creator1',
'c_time0','c_time1',
'user0','user1',
'd_time0','d_time1',
'detail0']
self.wt=['title','creator','create_time',
'viewer','finish_time','detail']
self.tabWidget = QtWidgets.QTabWidget(parentw)
self.tabWidget.setGeometry(QtCore.QRect(50, 10, 500, 2500))
self.tabWidget.setMinimumSize(QtCore.QSize(400, 400))
self.tabWidget.setTabsClosable(False)
self.tabWidget.setMovable(True)
self.tabWidget.setObjectName("tabWidget")
self.initTab()
# create tabs in tabwidget
def initTab(self,tabnum=2):
self.tabnum=tabnum
print('inittab')
self.tabs={}
for i in range(self.tabnum):
self.tabs[str(i)]=QtWidgets.QWidget()
self.tabs[str(i)].setObjectName("tab"+str(i))
self.tabWidget.addTab(self.tabs[str(i)], "")
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tabs[str(i)]),str(i))
self.initw_in_tab(self.tabs[str(i)])
print(self.tabs)
# add labels,textbrowser in tabs
def initw_in_tab(self,parentw):
w_in_tab={}
print('initw_in_tab')
for i in self.w:
w_in_tab[i]=QtWidgets.QLabel(parentw)
w_in_tab[i].setFont(self.font)
w_in_tab[i].setLayoutDirection(QtCore.Qt.LeftToRight)
w_in_tab[i].setAutoFillBackground(False)
w_in_tab[i].setFrameShape(QtWidgets.QFrame.Box)
w_in_tab[i].setFrameShadow(QtWidgets.QFrame.Raised)
w_in_tab[i].setLineWidth(1)
w_in_tab[i].setMidLineWidth(0)
w_in_tab[i].setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
w_in_tab[i].setIndent(3)
w_in_tab[i].setObjectName(i)
if self.w.index(i)%2 ==0:
w_in_tab[i].setGeometry(QtCore.QRect(20, 180 + self.w.index(i)*25, 59, 25))
w_in_tab[i].setText(self.wt[int(self.w.index(i)/2)])
else:
w_in_tab[i].setGeometry(QtCore.QRect(140, 180 +(self.w.index(i)-1)*25, 59, 25))
scrollArea = QtWidgets.QScrollArea(parentw)
scrollArea.setEnabled(True)
scrollArea.setGeometry(QtCore.QRect(140, 7*25+180, 341, 440))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(scrollArea.sizePolicy().hasHeightForWidth())
scrollArea.setSizePolicy(sizePolicy)
scrollArea.setMinimumSize(QtCore.QSize(200, 100))
scrollArea.setWidgetResizable(True)
scrollArea.setObjectName("scrollArea")
scrollAreaWidgetContents_2 = QtWidgets.QWidget()
scrollAreaWidgetContents_2.setGeometry(QtCore.QRect(0, 0, 322, 1600))
scrollAreaWidgetContents_2.setMinimumSize(QtCore.QSize(200, 1600))
scrollAreaWidgetContents_2.setObjectName("scrollAreaWidgetContents_2")
detail2 = QtWidgets.QTextBrowser(scrollAreaWidgetContents_2)
detail2.setGeometry(QtCore.QRect(0, 0, 321, 600))
detail2.setMinimumSize(QtCore.QSize(296, 192))
detail2.setObjectName("detail2")
scrollArea.setWidget(scrollAreaWidgetContents_2)
class Ui_MainWindow(object):
# setup main ui include calendar
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(997, 707)
MainWindow.setStyleSheet("")
self.centralWidget = QtWidgets.QWidget(MainWindow)
self.centralWidget.setObjectName("centralWidget")
self.centralWidget.setUpdatesEnabled(True)
self.calendarw = QtWidgets.QWidget(self.centralWidget)
self.calendarw.setGeometry(QtCore.QRect(560, 20, 361, 541))
self.calendarw.setObjectName("calendarw")
self.cal = QtWidgets.QCalendarWidget(self.calendarw)
self.cal.setGeometry(QtCore.QRect(0, 60, 361, 481))
self.cal.setFirstDayOfWeek(QtCore.Qt.Monday)
self.cal.setObjectName("cal")
self.cal_la = QtWidgets.QLabel(self.calendarw)
self.cal_la.setGeometry(QtCore.QRect(110, 20, 161, 31))
font = QtGui.QFont()
font.setPointSize(22)
self.cal_la.setFont(font)
self.cal_la.setAlignment(QtCore.Qt.AlignCenter)
self.cal_la.setObjectName("cal_la")
MainWindow.setCentralWidget(self.centralWidget)
MainWindow.setWindowTitle("MainWindow")
self.cal_la.setText("calendar")
#
# Ui_Tab(self.centralWidget)
# this makes me confused,I hope that when I clicked the date of the
# calendar ,then it will display the class of UI_tab.However it
# cant't work.
self.cal.clicked.connect(lambda x :Ui_Tab(self.centralWidget))
QtCore.QMetaObject.connectSlotsByName(MainWindow)
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_())
when I use the below code , it exactly does what I want it to do, but without clicking the calendar date.
Ui_Tab(self.centralWidget)
instead of
self.cal.clicked.connect(lambda x :Ui_Tab(self.centralWidget))
visit PyQt Window No Show
I just change the code below
self.cal.clicked.connect(lambda x :Ui_Tab(self.centralWidget))
to
self.cal.clicked.connect(Ui_Tab(self.centralWidget).show)

stacked widget page

i cannot go back to the first page of the stacked widget on, when i click the cancel button (from the cancel_button_clicked(self): function)
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMessageBox
class Ui_form(object):
def setupUi(self, form):
form.setObjectName("form")
form.resize(1000, 650)
self.groupBox = QtWidgets.QGroupBox(form)
self.groupBox.setGeometry(QtCore.QRect(530, 350, 451, 281))
self.groupBox.setObjectName("groupBox")
self.stackedWidget = QtWidgets.QStackedWidget(self.groupBox)
self.stackedWidget.setGeometry(QtCore.QRect(9, 19, 431, 241))
self.stackedWidget.setObjectName("stackedWidget")
self.page_1 = QtWidgets.QWidget()
self.page_1.setObjectName("page_1")
self.login_button = QtWidgets.QPushButton(self.page_1)
self.login_button.setGeometry(QtCore.QRect(20, 210, 75, 23))
self.login_button.setObjectName("login_button")
self.register_button = QtWidgets.QPushButton(self.page_1)
self.register_button.setGeometry(QtCore.QRect(180, 210, 75, 23))
self.register_button.setObjectName("register_button")
self.exit_button = QtWidgets.QPushButton(self.page_1)
self.exit_button.setGeometry(QtCore.QRect(330, 210, 75, 23))
self.exit_button.setObjectName("exit_button")
self.username_line = QtWidgets.QLineEdit(self.page_1)
self.username_line.setGeometry(QtCore.QRect(230, 40, 113, 20))
self.username_line.setObjectName("username_line")
self.password_line = QtWidgets.QLineEdit(self.page_1)
self.password_line.setGeometry(QtCore.QRect(230, 110, 113, 20))
self.password_line.setObjectName("password_line")
self.username_label = QtWidgets.QLabel(self.page_1)
self.username_label.setGeometry(QtCore.QRect(60, 40, 81, 16))
self.username_label.setObjectName("username_label")
self.password_label = QtWidgets.QLabel(self.page_1)
self.password_label.setGeometry(QtCore.QRect(60, 110, 61, 16))
self.password_label.setObjectName("password_label")
self.stackedWidget.addWidget(self.page_1)
self.page_2 = QtWidgets.QWidget()
self.page_2.setObjectName("page_2")
self.registeruser_label = QtWidgets.QLabel(self.page_2)
self.registeruser_label.setGeometry(QtCore.QRect(60, 33, 71, 20))
self.registeruser_label.setObjectName("registeruser_label")
self.registerepass_label = QtWidgets.QLabel(self.page_2)
self.registerepass_label.setGeometry(QtCore.QRect(60, 100, 61, 16))
self.registerepass_label.setObjectName("registerepass_label")
self.registeruser_line = QtWidgets.QLineEdit(self.page_2)
self.registeruser_line.setGeometry(QtCore.QRect(240, 40, 113, 20))
self.registeruser_line.setObjectName("registeruser_line")
self.registerpass_line = QtWidgets.QLineEdit(self.page_2)
self.registerpass_line.setGeometry(QtCore.QRect(240, 100, 113, 20))
self.registerpass_line.setObjectName("registerpass_line")
self.signup_button = QtWidgets.QPushButton(self.page_2)
self.signup_button.setGeometry(QtCore.QRect(70, 190, 75, 23))
self.signup_button.setObjectName("signup_button")
self.cancel_button = QtWidgets.QPushButton(self.page_2)
self.cancel_button.setGeometry(QtCore.QRect(270, 190, 75, 23))
self.cancel_button.setObjectName("cancel_button")
self.stackedWidget.addWidget(self.page_2)
self.retranslateUi(form)
self.stackedWidget.setCurrentIndex(0)
self.login_button.clicked.connect(self.login_button_clicked)
self.register_button.clicked.connect(self.register_button_clicked)
self.cancel_button.clicked.connect(self.cancel_button_clicked)
self.exit_button.clicked.connect(self.exit_button_clicked)
def retranslateUi(self, form):
_translate = QtCore.QCoreApplication.translate
form.setWindowTitle(_translate("form", "Form"))
self.groupBox.setTitle(_translate("form", "USER"))
self.login_button.setText(_translate("form", "LOG IN"))
self.register_button.setText(_translate("form", "REGISTER"))
self.exit_button.setText(_translate("form", "EXIT"))
self.username_label.setText(_translate("form", "USERNAME"))
self.password_label.setText(_translate("form", "PASSWORD"))
self.registeruser_label.setText(_translate("form", "USERNAME"))
self.registerepass_label.setText(_translate("form", "PASSWORD"))
self.signup_button.setText(_translate("form", "SIGN UP"))
self.cancel_button.setText(_translate("form", "CANCEL"))
def login_button_clicked(self):
file = open('user.txt','r')
for line in file:
us, pa = line.rstrip().split(';')
if self.username_line.text() == us and self.password_line.text() == pa:
QMessageBox.information(QMessageBox(), "Login", "LOGIN SUCCESS!")
break
else:
QMessageBox.information(QMessageBox(), "login", "LOGIN FAILED!")
def register_button_clicked(self):
self.stackedWidget.setCurrentIndex(1)
def cancel_button_clicked(self):
self.stackedWidget.setCurrentIndex(-1)
def exit_button_clicked(self):
self.close()
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
LOGIN_window = QtWidgets.QDialog()
LOGIN = Ui_form()
LOGIN.setupUi(LOGIN_window)
LOGIN_window.show()
sys.exit(app.exec_())
It is not advisable to modify the class that Qt Designer generates, and worse if you are a beginner. The most recommended is to create a class that implements logic and use the design already created.
To do this you must choose the appropriate Widget, if you used as a template to MainWindow you should use QMainWindow, if you use Widget you must use QWidget and if you use any of the variants of Dialog you should use QDialog as I think this is the case.
Since the task is simple it is not necessary to create a method like slot, we could use a lambda function: lambda: self.stackedWidget.setCurrentIndex(1)
All of the above I implemented in the following code:
class Dialog(QtWidgets.QDialog, Ui_form):
def __init__(self, parent=None):
QtWidgets.QDialog.__init__(self, parent)
self.setupUi(self)
self.stackedWidget.setCurrentIndex(0)
self.login_button.clicked.connect(self.Confirm_Button_Clicked)
self.register_button.clicked.connect(lambda: self.stackedWidget.setCurrentIndex(1))
self.cancel_button.clicked.connect(self.cancel_button_clicked)
def Confirm_Button_Clicked(self):
file = open('user.txt','r')
[...]
def cancel_button_clicked(self):
self.stackedWidget.setCurrentIndex(0)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = Dialog()
w.show()
sys.exit(app.exec_())
Note: If you want to return to the first page you should place the value of 0 as the current index, remember that the indexes start from 0.

How to print in a QDialog the output of a function? With pyqt

I have a problem displaying the output of a function in a qdialog of pyqt.
My code is as follows:
import sys
import os
import glob
import shutil
import json
import datetime
import time
import requests
from multiprocessing import Queue
start_time = time.time()
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QDialog, QPushButton, QLabel, QScrollArea, QProgressBar, QTextEdit
noreports = len(glob.glob('*.txt'))
class Dialogo(QDialog):
def __init__(self):
QDialog.__init__(self)
self.resize(400, 380)
self.nombre = QLabel(self)
self.nombre.setGeometry(QtCore.QRect(30, 20, 171, 17))
self.nombre.setObjectName("nombre")
self.label = QLabel(self)
self.label.setGeometry(QtCore.QRect(30, 50, 121, 17))
self.label.setObjectName("label")
self.pushButton = QPushButton(self)
self.pushButton.setGeometry(QtCore.QRect(260, 310, 86, 28))
self.pushButton.setObjectName("pushButton")
self.scrollArea = QScrollArea(self)
self.scrollArea.setGeometry(QtCore.QRect(30, 120, 341, 171))
self.scrollArea.setWidgetResizable(True)
self.scrollArea.setObjectName("scrollArea")
self.scrollAreaWidgetContents = QtWidgets.QWidget()
self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 337, 167))
self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
self.scrollArea.setWidget(self.scrollAreaWidgetContents)
self.progressBar = QProgressBar(self)
self.progressBar.setGeometry(QtCore.QRect(30, 80, 341, 23))
self.progressBar.setProperty("value", 0)
self.progressBar.setObjectName("progressBar")
self.textEdit = QTextEdit(self)
self.scrollArea.setWidget(self.textEdit)
self.retranslateUi(self)
QtCore.QMetaObject.connectSlotsByName(self)
def retranslateUi(self, Dialogo):
global noreports
_translate = QtCore.QCoreApplication.translate
self.setWindowTitle(_translate("Dialog", "Process..."))
self.label.setText(_translate("Dialog", "Files:" + str(noreports)))
self.pushButton.setText(_translate("Dialog", "Terminate"))
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(321, 247)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("../../../../api-server/favicon.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
Form.setWindowIcon(icon)
Form.setWindowOpacity(0.98)
Form.setProperty("sunrise", QtGui.QPixmap("../../../../api-server/ejemplo.png"))
self.lineEdit = QtWidgets.QLineEdit(Form)
self.lineEdit.setGeometry(QtCore.QRect(20, 130, 281, 51))
self.lineEdit.setAutoFillBackground(True)
self.lineEdit.setObjectName("lineEdit")
self.DescriptLbl = QtWidgets.QLabel(Form)
self.DescriptLbl.setGeometry(QtCore.QRect(20, 100, 281, 20))
self.DescriptLbl.setObjectName("DescriptLbl")
self.showinformBtn = QtWidgets.QPushButton(Form)
self.showinformBtn.setGeometry(QtCore.QRect(30, 190, 161, 31))
self.showinformBtn.setStyleSheet("background:rgb(110, 175, 255);\n"
"color:rgb(36, 36, 36);\n"
"border-radius:3px;\n"
"border-color:black;")
self.showinformBtn.setObjectName("showinformBtn")
self.dialogo = Dialogo()
self.showinformBtn.clicked.connect(self.abrirDialogo)
#self.showinformBtn.clicked.connect(self.showinform)
self.CancelarBtn = QtWidgets.QPushButton(Form)
self.CancelarBtn.setGeometry(QtCore.QRect(220, 190, 75, 31))
self.CancelarBtn.setStyleSheet("background:rgb(226, 76, 31);\n"
"color:rgb(36, 36, 36);\n"
"border-radius:3px;\n"
"border-color:black;")
self.CancelarBtn.setObjectName("CancelarBtn")
self.label_2 = QtWidgets.QLabel(Form)
self.label_2.setGeometry(QtCore.QRect(20, 220, 311, 20))
self.label_2.setTextFormat(QtCore.Qt.RichText)
self.label_2.setScaledContents(True)
self.label_2.setOpenExternalLinks(True)
self.label_2.setTextInteractionFlags(QtCore.Qt.LinksAccessibleByKeyboard|QtCore.Qt.LinksAccessibleByMouse|QtCore.Qt.TextBrowserInteraction|QtCore.Qt.TextEditable|QtCore.Qt.TextEditorInteraction|QtCore.Qt.TextSelectableByKeyboard|QtCore.Qt.TextSelectableByMouse)
self.label_2.setObjectName("label_2")
self.showinformLbl = QtWidgets.QLabel(Form)
self.showinformLbl.setGeometry(QtCore.QRect(20, 30, 281, 41))
font = QtGui.QFont()
font.setPointSize(22)
self.showinformLbl.setFont(font)
self.showinformLbl.setObjectName("showinformLbl")
self.imagen = QtWidgets.QLabel(Form)
self.imagen.setGeometry(QtCore.QRect(-80, 0, 221, 231))
self.imagen.setText("")
self.imagen.setPixmap(QtGui.QPixmap("max.png"))
self.imagen.setScaledContents(False)
self.imagen.setIndent(-1)
self.imagen.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
self.imagen.setObjectName("imagen")
self.imagen.raise_()
self.lineEdit.raise_()
self.DescriptLbl.raise_()
self.showinformBtn.raise_()
self.CancelarBtn.raise_()
self.label_2.raise_()
self.showinformLbl.raise_()
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "api-server"))
self.lineEdit.setToolTip(_translate("Form", "<html><head/><body><p>write.</p></body></html>"))
self.lineEdit.setWhatsThis(_translate("Form", "<html><head/><body><p>write.</p></body></html>"))
self.DescriptLbl.setText(_translate("Form", "descrip inform."))
self.showinformBtn.setToolTip(_translate("Form", "<html><head/><body><p>Create report.</p></body></html>"))
self.showinformBtn.setText(_translate("Form", "show inform"))
self.CancelarBtn.setToolTip(_translate("Form", "<html><head/><body><p>Cancel.</p></body></html>"))
self.CancelarBtn.setText(_translate("Form", "Cancel"))
self.label_2.setText(_translate("Form", "<html><head/><body><p>Visit api-server. ;)</p></body></html>"))
self.showinformLbl.setText(_translate("Form", "show inform."))
def abrirDialogo(self):
nombreinform = self.lineEdit.text()
self.dialogo.nombre.setText('inform:' + nombreinform)
self.dialogo.show()
self.showinform()
def showinform(self):
current_time = datetime.datetime.today().strftime("%Y-%b-%dT%H_%M")
alle = glob.glob('*.txt')
counterfile = noreports
porcentotal = 0
suma = 100/counterfile
counterbien = 0
for file in alle:
porcentotal += float(suma)
avance = round(float(porcentotal), 0)
self.dialogo.progressBar.setProperty("value", format(avance))
self.dialogo.textEdit.setText(file + format(avance))
print ('{!r} %'.format(avance))
dict = '{!r} %'.format(avance)
f = open(file,'w')
f.write('result = ' + repr(dict) + '\n')
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Form = QtWidgets.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_())
The code is executed but not displayed in Dialog, only the labels but not the progress bar.
Why does this happen?
The problem is that you are using the format function badly, this is used when you have a string and you want to insert data with a certain format.
The setProperty function requires as first parameter the property you want to assign, and a second value of the type that requires the property, in your case value requires an integer value so you can pass the percentage directly without needing to change it to string.
If you read many files this can block the main thread where the GUI is drawn, to solve this you must use QApplication.processEvents()
def showinform(self):
current_time = datetime.datetime.today().strftime("%Y-%b-%dT%H_%M")
alle = glob.glob('*.txt')
counterfile = noreports
porcentotal = 0
suma = 100/counterfile
counterbien = 0
for file in alle:
porcentotal += float(suma)
avance = round(float(porcentotal), 0)
self.dialogo.progressBar.setProperty("value", avance)
self.dialogo.textEdit.append("{}{}".format(file, avance))
print ('{!r} %'.format(avance))
dict = '{!r} %'.format(avance)
QApplication.processEvents()
f = open(file,'w')
f.write('result = ' + repr(dict) + '\n')
Note: I have changed the setText function to append in QTextEdit so that it is added and not overwritten.
Instead of using setProperty you could use the setValue function of QProgressBar:
self.dialogo.progressBar.setValue(avance)
Another recommendation is to verify that the counterfile is non-zero since it could generate an exception for the division.

Categories

Resources