So I have created a stacked widget with 2 pages. In the first page, I have one button " Sign In ". In the second page, I have One button " Logout"
I want that, if I click on the "Sign in" button it will open another page/widget with the " Logout " button in the stacked widget.
First Page Index = 0
Second page index = 1
Sign in button object name = pushButton
Logout button object name = LogoutBtn
this is my code from PyQt5 :
class Ui_StackedWidget(object):
def setupUi(self, StackedWidget):
StackedWidget.setObjectName("StackedWidget")
StackedWidget.resize(470, 406)
self.page1 = QtWidgets.QWidget()
self.page1.setObjectName("page1")
self.label = QtWidgets.QLabel(self.page1)
self.label.setGeometry(QtCore.QRect(150, 170, 35, 10))
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(self.page1)
self.label_2.setGeometry(QtCore.QRect(150, 200, 35, 10))
self.label_2.setObjectName("label_2")
self.pushButton = QtWidgets.QPushButton(self.page1)
self.pushButton.setGeometry(QtCore.QRect(230, 230, 56, 17))
self.pushButton.setObjectName("pushButton")
self.lineEdit = QtWidgets.QLineEdit(self.page1)
self.lineEdit.setGeometry(QtCore.QRect(200, 170, 113, 16))
self.lineEdit.setObjectName("lineEdit")
self.lineEdit_2 = QtWidgets.QLineEdit(self.page1)
self.lineEdit_2.setGeometry(QtCore.QRect(200, 200, 113, 16))
self.lineEdit_2.setObjectName("lineEdit_2")
self.label_3 = QtWidgets.QLabel(self.page1)
self.label_3.setGeometry(QtCore.QRect(230, 120, 35, 10))
self.label_3.setObjectName("label_3")
StackedWidget.addWidget(self.page1)
self.page = QtWidgets.QWidget()
self.page.setObjectName("page")
self.label_4 = QtWidgets.QLabel(self.page)
self.label_4.setGeometry(QtCore.QRect(180, 70, 101, 16))
self.label_4.setObjectName("label_4")
self.label_5 = QtWidgets.QLabel(self.page)
self.label_5.setGeometry(QtCore.QRect(190, 110, 91, 16))
self.label_5.setObjectName("label_5")
self.CreateBtn = QtWidgets.QPushButton(self.page)
self.CreateBtn.setGeometry(QtCore.QRect(200, 160, 56, 17))
self.CreateBtn.setObjectName("CreateBtn")
self.ShowBtn = QtWidgets.QPushButton(self.page)
self.ShowBtn.setGeometry(QtCore.QRect(200, 190, 56, 17))
self.ShowBtn.setObjectName("ShowBtn")
self.DeleteBtn = QtWidgets.QPushButton(self.page)
self.DeleteBtn.setGeometry(QtCore.QRect(200, 220, 56, 17))
self.DeleteBtn.setObjectName("DeleteBtn")
self.UpdateBtn = QtWidgets.QPushButton(self.page)
self.UpdateBtn.setGeometry(QtCore.QRect(200, 250, 56, 17))
self.UpdateBtn.setObjectName("UpdateBtn")
self.LogoutBtn = QtWidgets.QPushButton(self.page)
self.LogoutBtn.setGeometry(QtCore.QRect(320, 320, 56, 17))
self.LogoutBtn.setObjectName("LogoutBtn")
StackedWidget.addWidget(self.page)
self.page_2 = QtWidgets.QWidget()
self.page_2.setObjectName("page_2")
self.label_6 = QtWidgets.QLabel(self.page_2)
self.label_6.setGeometry(QtCore.QRect(150, 90, 141, 16))
self.label_6.setObjectName("label_6")
self.Logout1Btn = QtWidgets.QPushButton(self.page_2)
self.Logout1Btn.setGeometry(QtCore.QRect(330, 320, 56, 17))
self.Logout1Btn.setObjectName("Logout1Btn")
self.main1Btn = QtWidgets.QPushButton(self.page_2)
self.main1Btn.setGeometry(QtCore.QRect(260, 320, 56, 17))
self.main1Btn.setObjectName("main1Btn")
self.label_7 = QtWidgets.QLabel(self.page_2)
self.label_7.setGeometry(QtCore.QRect(200, 180, 35, 10))
self.label_7.setObjectName("label_7")
StackedWidget.addWidget(self.page_2)
self.retranslateUi(StackedWidget)
QtCore.QMetaObject.connectSlotsByName(StackedWidget)
then I created a function switching ( i saw a reference in StackOverflow ) _
def switching(self):
self.ui = Ui_StackedWidget()
self.ui.setupUi(self)
self.ui.LogoutBtn.clicked.connect(lambda : self.ui.StackedWidget.setCurrentIndex(0))
self.ui.pushButton.clicked.connect(lambda : self.ui.StackedWidget.setCurrentIndex(1))
But it doesn't switch between windows.
According to the code you provide, I deduce that you used StackedWidget as a template, so the class you use fills in ui to inherit from that class.
An error that I see in your code is self.ui.StackedWidget since ui has no attribute called StackedWidget, so you should throw an exception.
Considering the above, the solution is:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_StackedWidget(object):
def setupUi(self, StackedWidget):
# ...
def retranslateUi(self, StackedWidget):
# ...
class StackedWidget(QtWidgets.QStackedWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.ui = Ui_StackedWidget()
self.ui.setupUi(self)
self.ui.LogoutBtn.clicked.connect(lambda : self.setCurrentIndex(0))
self.ui.pushButton.clicked.connect(lambda : self.setCurrentIndex(1))
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = StackedWidget()
w.show()
sys.exit(app.exec_())
Related
Im trying to get some push buttons to blink from a QtDesigner file, but im having trouble using the timer function to change the background of the button.
I was already helped by someone here and their code works great, but I cant seem to integrate the code to what I already have.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(QtWidgets.QMainWindow):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1309, 813)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(50, 30, 251, 41))
font = QtGui.QFont()
font.setPointSize(36)
self.label.setFont(font)
self.label.setObjectName("label")
self.voltage_percent = QtWidgets.QLCDNumber(self.centralwidget)
self.voltage_percent.setGeometry(QtCore.QRect(80, 170, 141, 91))
self.voltage_percent.setSmallDecimalPoint(True)
self.voltage_percent.setDigitCount(1)
self.voltage_percent.setProperty("intValue", 5)
self.voltage_percent.setObjectName("voltage_percent")
self.label_2 = QtWidgets.QLabel(self.centralwidget)
self.label_2.setGeometry(QtCore.QRect(1070, 30, 111, 51))
font = QtGui.QFont()
font.setPointSize(36)
self.label_2.setFont(font)
self.label_2.setObjectName("label_2")
self.modeTable = QtWidgets.QTableView(self.centralwidget)
self.modeTable.setGeometry(QtCore.QRect(970, 90, 321, 411))
self.modeTable.setObjectName("modeTable")
self.label_12 = QtWidgets.QLabel(self.centralwidget)
self.label_12.setGeometry(QtCore.QRect(170, 190, 51, 61))
font = QtGui.QFont()
font.setPointSize(48)
self.label_12.setFont(font)
self.label_12.setObjectName("label_12")
self.label_13 = QtWidgets.QLabel(self.centralwidget)
self.label_13.setGeometry(QtCore.QRect(580, 30, 91, 41))
font = QtGui.QFont()
font.setPointSize(36)
self.label_13.setFont(font)
self.label_13.setObjectName("label_13")
self.flags_table = QtWidgets.QGraphicsView(self.centralwidget)
self.flags_table.setGeometry(QtCore.QRect(370, 90, 541, 401))
self.flags_table.setObjectName("flags_table")
self.powerup_button = QtWidgets.QPushButton(self.centralwidget)
self.powerup_button.setGeometry(QtCore.QRect(380, 110, 111, 81))
self.powerup_button.setText("")
self.powerup_button.setObjectName("powerup_button")
self.flag = True
timer = QtCore.QTimer(self, interval=1000)
timer.timeout.connect(self.update)
timer.start(1000)
def update_color (self):
if self.flag==True:
self.powerup_button.setStyleSheet("background-color:none;")
else:
self.powerup_button.setStyleSheet("background-color: green;")
self.flag = False
I only included the part where I created my push button for simplicity, there are many more but I figured the same solution applies to all of them since they're the same. Am I just applying the timer wrong? the gui pops up, but the button I want to blink wont blink when I run the program (the powerup button)
Try it:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(QtWidgets.QMainWindow):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1309, 813)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(50, 30, 251, 41))
font = QtGui.QFont()
font.setPointSize(36)
self.label.setFont(font)
self.label.setObjectName("label")
self.voltage_percent = QtWidgets.QLCDNumber(self.centralwidget)
self.voltage_percent.setGeometry(QtCore.QRect(80, 170, 141, 91))
self.voltage_percent.setSmallDecimalPoint(True)
self.voltage_percent.setDigitCount(1)
self.voltage_percent.setProperty("intValue", 5)
self.voltage_percent.setObjectName("voltage_percent")
self.label_2 = QtWidgets.QLabel(self.centralwidget)
self.label_2.setGeometry(QtCore.QRect(1070, 30, 111, 51))
font = QtGui.QFont()
font.setPointSize(36)
self.label_2.setFont(font)
self.label_2.setObjectName("label_2")
self.modeTable = QtWidgets.QTableView(self.centralwidget)
self.modeTable.setGeometry(QtCore.QRect(970, 90, 321, 411))
self.modeTable.setObjectName("modeTable")
self.label_12 = QtWidgets.QLabel(self.centralwidget)
self.label_12.setGeometry(QtCore.QRect(170, 190, 51, 61))
font = QtGui.QFont()
font.setPointSize(48)
self.label_12.setFont(font)
self.label_12.setObjectName("label_12")
self.label_13 = QtWidgets.QLabel(self.centralwidget)
self.label_13.setGeometry(QtCore.QRect(580, 30, 91, 41))
font = QtGui.QFont()
font.setPointSize(36)
self.label_13.setFont(font)
self.label_13.setObjectName("label_13")
self.flags_table = QtWidgets.QGraphicsView(self.centralwidget)
self.flags_table.setGeometry(QtCore.QRect(370, 90, 541, 401))
self.flags_table.setObjectName("flags_table")
self.powerup_button = QtWidgets.QPushButton(self.centralwidget)
self.powerup_button.setGeometry(QtCore.QRect(380, 110, 111, 81))
self.powerup_button.setText(" ")
self.powerup_button.setObjectName("powerup_button")
self.flag = True
timer = QtCore.QTimer(MainWindow) # +++
timer.timeout.connect(self.update_color)
timer.start(1000)
MainWindow.setCentralWidget(self.centralwidget)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def update_color (self):
if self.flag: #==True:
self.powerup_button.setStyleSheet("#powerup_button {background-color:none;}")
else:
self.powerup_button.setStyleSheet("#powerup_button {background-color: green;}")
# self.flag = False
self.flag = not self.flag # +
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
app.setStyle('Windows')
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
I used QTimeEdit to edit time. But when I clicked "ok" the output is HOUR: 16 MINUTE: 8, no matter what number I put in QTimeEdit. Thus, I want to know what function I must add to correct the set time in QTimeEdit.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_EditTime(object):
def setupUi(self, EditTime):
EditTime.setObjectName("EditTime")
EditTime.resize(392, 293)
EditTime.setAutoFillBackground(False)
self.timeEdit = QtWidgets.QTimeEdit(EditTime)
self.timeEdit.setGeometry(QtCore.QRect(140, 160, 118, 22))
self.timeEdit.setMaximumDateTime(QtCore.QDateTime(QtCore.QDate(1999, 12, 31), QtCore.QTime(23, 59, 59)))
self.timeEdit.setMaximumDate(QtCore.QDate(1999, 12, 31))
self.timeEdit.setMinimumDate(QtCore.QDate(1999, 12, 31))
self.timeEdit.setMaximumTime(QtCore.QTime(23, 59, 59))
self.timeEdit.setMinimumTime(QtCore.QTime(00, 00, 00))
self.timeEdit.setCurrentSection(QtWidgets.QDateTimeEdit.HourSection)
self.timeEdit.setTimeSpec(QtCore.Qt.OffsetFromUTC)
self.timeEdit.setTime(QtCore.QTime(24,0,0))
self.timeEdit.setObjectName("timeEdit")
self.HourLCD = QtWidgets.QLCDNumber(EditTime)
self.HourLCD.setGeometry(QtCore.QRect(60, 70, 111, 51))
self.HourLCD.setObjectName("HourLCD")
self.MinuteLCD = QtWidgets.QLCDNumber(EditTime)
self.MinuteLCD.setGeometry(QtCore.QRect(200, 70, 111, 51))
self.MinuteLCD.setObjectName("MinuteLCD")
self.OK = QtWidgets.QPushButton(EditTime)
self.OK.setGeometry(QtCore.QRect(160, 230, 75, 23))
self.OK.setObjectName("OK")
self.label = QtWidgets.QLabel(EditTime)
self.label.setGeometry(QtCore.QRect(90, 46, 31, 20))
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(EditTime)
self.label_2.setGeometry(QtCore.QRect(230, 50, 47, 13))
self.label_2.setObjectName("label_2")
self.retranslateUi(EditTime)
QtCore.QMetaObject.connectSlotsByName(EditTime)
self.OK.clicked.connect(self.connect)
def connect(self):
self.HourLCD.display(self.timeEdit.HourSection)
self.MinuteLCD.display(self.timeEdit.MinuteSection)
I expect the output base on the QTimeEdit
HourSection and MinuteSection does not represent the time and the minute but the sections of the QTimeEdit. Instead you should get the time using the time() method, and using the latter use hour() and minute() to get the hour and the minute, respectively.
Also, you should not modify the code generated by Qt Designer as PyQt indicates, instead you should create another class that inherits from the appropriate widget and that uses the initial class as an interface. For more information I recommend reading this.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_EditTime(object):
def setupUi(self, EditTime):
EditTime.setObjectName("EditTime")
EditTime.resize(392, 293)
EditTime.setAutoFillBackground(False)
self.timeEdit = QtWidgets.QTimeEdit(EditTime)
self.timeEdit.setGeometry(QtCore.QRect(140, 160, 118, 22))
self.timeEdit.setMaximumDateTime(QtCore.QDateTime(QtCore.QDate(1999, 12, 31), QtCore.QTime(23, 59, 59)))
self.timeEdit.setMaximumDate(QtCore.QDate(1999, 12, 31))
self.timeEdit.setMinimumDate(QtCore.QDate(1999, 12, 31))
self.timeEdit.setMaximumTime(QtCore.QTime(23, 59, 59))
self.timeEdit.setMinimumTime(QtCore.QTime(00, 00, 00))
self.timeEdit.setCurrentSection(QtWidgets.QDateTimeEdit.HourSection)
self.timeEdit.setTimeSpec(QtCore.Qt.OffsetFromUTC)
self.timeEdit.setTime(QtCore.QTime(24,0,0))
self.timeEdit.setObjectName("timeEdit")
self.HourLCD = QtWidgets.QLCDNumber(EditTime)
self.HourLCD.setGeometry(QtCore.QRect(60, 70, 111, 51))
self.HourLCD.setObjectName("HourLCD")
self.MinuteLCD = QtWidgets.QLCDNumber(EditTime)
self.MinuteLCD.setGeometry(QtCore.QRect(200, 70, 111, 51))
self.MinuteLCD.setObjectName("MinuteLCD")
self.OK = QtWidgets.QPushButton(EditTime)
self.OK.setGeometry(QtCore.QRect(160, 230, 75, 23))
self.OK.setObjectName("OK")
self.label = QtWidgets.QLabel(EditTime)
self.label.setGeometry(QtCore.QRect(90, 46, 31, 20))
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(EditTime)
self.label_2.setGeometry(QtCore.QRect(230, 50, 47, 13))
self.label_2.setObjectName("label_2")
# self.retranslateUi(EditTime)
QtCore.QMetaObject.connectSlotsByName(EditTime)
class Widget(QtWidgets.QWidget, Ui_EditTime):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
self.setupUi(self)
self.OK.clicked.connect(self.onClicked)
#QtCore.pyqtSlot()
def onClicked(self):
t = self.timeEdit.time()
self.HourLCD.display(t.hour())
self.MinuteLCD.display(t.minute())
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
Apparently a bit slower than eyllanesc and with significant enough differences to post it anyway. Remarks are the same.
Personally I'm more for import statements as advised by PEP docs and for oversight having connections made in their own function.
import sys, time
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication
class Ui_EditTime(object):
def setupUi(self, EditTime):
EditTime.setObjectName("EditTime")
EditTime.resize(392, 293)
EditTime.setAutoFillBackground(False)
self.timeEdit = QtWidgets.QTimeEdit(EditTime)
self.timeEdit.setGeometry(QtCore.QRect(140, 160, 118, 22))
self.timeEdit.setMaximumDateTime(QtCore.QDateTime(QtCore.QDate(1999, 12, 31), QtCore.QTime(23, 59, 59)))
self.timeEdit.setMaximumDate(QtCore.QDate(1999, 12, 31))
self.timeEdit.setMinimumDate(QtCore.QDate(1999, 12, 31))
self.timeEdit.setMaximumTime(QtCore.QTime(23, 59, 59))
self.timeEdit.setMinimumTime(QtCore.QTime(00, 00, 00))
self.timeEdit.setCurrentSection(QtWidgets.QDateTimeEdit.HourSection)
self.timeEdit.setTimeSpec(QtCore.Qt.OffsetFromUTC)
self.timeEdit.setTime(QtCore.QTime(24,0,0))
self.timeEdit.setObjectName("timeEdit")
self.HourLCD = QtWidgets.QLCDNumber(EditTime)
self.HourLCD.setGeometry(QtCore.QRect(60, 70, 111, 51))
self.HourLCD.setObjectName("HourLCD")
self.MinuteLCD = QtWidgets.QLCDNumber(EditTime)
self.MinuteLCD.setGeometry(QtCore.QRect(200, 70, 111, 51))
self.MinuteLCD.setObjectName("MinuteLCD")
self.OK = QtWidgets.QPushButton(EditTime)
self.OK.setGeometry(QtCore.QRect(160, 230, 75, 23))
self.OK.setObjectName("OK")
self.label = QtWidgets.QLabel(EditTime)
self.label.setGeometry(QtCore.QRect(90, 46, 31, 20))
self.label.setObjectName("label")
self.label_2 = QtWidgets.QLabel(EditTime)
self.label_2.setGeometry(QtCore.QRect(230, 50, 47, 13))
self.label_2.setObjectName("label_2")
self.retranslateUi(EditTime)
QtCore.QMetaObject.connectSlotsByName(EditTime)
def retranslateUi(self, EditTime):
_translate = QtCore.QCoreApplication.translate
class EditTime(QtWidgets.QWidget, Ui_EditTime):
def __init__(self, parent=None):
super(EditTime, self).__init__(parent) # make flexible MainWindow class.
self.setupUi(self)
self.connections() # oversight off all your connections there are made in your application.
def connections(self):
self.OK.clicked.connect(self.connect)
def connect(self):
t_mod = self.timeEdit.time()
self.HourLCD.display(t_mod.hour())
self.MinuteLCD.display(t_mod.minute())
if __name__ == '__main__':
print ('Starting QTimeEdit application')
sys.stdout.flush() # shows output directly in an editor.
app = QApplication(sys.argv)
window = EditTime()
window.show()
sys.exit(app.exec_())
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.
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.
I'm new to PyQt5 and want to code a small programm
I designed two Windows in QT Designer and convertet them into a py Script.
Afterwards i merged both into one file (maybe my attempt is totaly wrong - so pls correct me)
When the program starts I get a small Window with some Radio Buttons and OK and Cancel.
I want to start another Window by clicking on OK. (This works fine)
My problem is, that the initial Window stays active in Background. (How can I close only the initial window? all my attempts have closed the whole programm. I do not know what I have to change?
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class CLASS_WELCOME(object):
def setupUi(self, Welcome):
Welcome.setObjectName("Welcome")
Welcome.resize(204, 215)
Welcome.setWindowTitle("Welcome")
Welcome.setWhatsThis("")
self.buttonBox = QtWidgets.QDialogButtonBox(Welcome)
self.buttonBox.setGeometry(QtCore.QRect(0, 180, 191, 32))
self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
self.buttonBox.setObjectName("buttonBox")
self.frame = QtWidgets.QFrame(Welcome)
self.frame.setGeometry(QtCore.QRect(20, 40, 151, 131))
self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame.setObjectName("frame")
self.radioButton = QtWidgets.QRadioButton(self.frame)
self.radioButton.setGeometry(QtCore.QRect(10, 10, 116, 22))
self.radioButton.setObjectName("radioButton")
self.radioButton_2 = QtWidgets.QRadioButton(self.frame)
self.radioButton_2.setGeometry(QtCore.QRect(10, 40, 116, 22))
self.radioButton_2.setObjectName("radioButton_2")
self.radioButton_3 = QtWidgets.QRadioButton(self.frame)
self.radioButton_3.setGeometry(QtCore.QRect(10, 70, 116, 22))
self.radioButton_3.setObjectName("radioButton_3")
self.radioButton_4 = QtWidgets.QRadioButton(self.frame)
self.radioButton_4.setGeometry(QtCore.QRect(10, 100, 116, 22))
self.radioButton_4.setObjectName("radioButton_4")
self.label = QtWidgets.QLabel(Welcome)
self.label.setGeometry(QtCore.QRect(10, 10, 191, 17))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label.setFont(font)
self.label.setObjectName("label")
self.retranslateUi(Welcome)
self.buttonBox.accepted.connect(self.onOK)
self.buttonBox.rejected.connect(Welcome.reject)
QtCore.QMetaObject.connectSlotsByName(Welcome)
self.Gui = CLASS_GUI()
def retranslateUi(self, Welcome):
_translate = QtCore.QCoreApplication.translate
self.radioButton.setText(_translate("Welcome", "blue"))
self.radioButton_2.setText(_translate("Welcome", "green"))
self.radioButton_3.setText(_translate("Welcome", "red"))
self.radioButton_4.setText(_translate("Welcome", "yellow"))
self.label.setText(_translate("Welcome", "Mensch aergere dich nicht!"))
def onOK(self):
MenschUi = QtWidgets.QDialog()
MenschUi.ui = CLASS_GUI()
MenschUi.ui.setupUi(MenschUi)
MenschUi.exec_()
class CLASS_GUI(object):
def setupUi(self, MenschUi):
MenschUi.setObjectName("MenschUi")
MenschUi.resize(640, 485)
self.Abbrechen = QtWidgets.QDialogButtonBox(MenschUi)
self.Abbrechen.setGeometry(QtCore.QRect(290, 450, 341, 32))
self.Abbrechen.setOrientation(QtCore.Qt.Horizontal)
self.Abbrechen.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel)
self.Abbrechen.setCenterButtons(False)
self.Abbrechen.setObjectName("Abbrechen")
self.frame = QtWidgets.QFrame(MenschUi)
self.frame.setGeometry(QtCore.QRect(100, 10, 531, 431))
self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame.setObjectName("frame")
self.Spieler = QtWidgets.QLabel(MenschUi)
self.Spieler.setGeometry(QtCore.QRect(10, 20, 66, 17))
self.Spieler.setObjectName("Spieler")
self.Computer = QtWidgets.QLabel(MenschUi)
self.Computer.setGeometry(QtCore.QRect(10, 100, 66, 17))
self.Computer.setObjectName("Computer")
self.LCDSpieler = QtWidgets.QLCDNumber(MenschUi)
self.LCDSpieler.setGeometry(QtCore.QRect(20, 40, 21, 23))
self.LCDSpieler.setDigitCount(1)
self.LCDSpieler.setObjectName("LCDSpieler")
self.LCDComputer = QtWidgets.QLCDNumber(MenschUi)
self.LCDComputer.setGeometry(QtCore.QRect(20, 130, 21, 23))
self.LCDComputer.setDigitCount(1)
self.LCDComputer.setObjectName("LCDComputer")
self.wuerfeln = QtWidgets.QPushButton(MenschUi)
self.wuerfeln.setGeometry(QtCore.QRect(10, 70, 81, 27))
self.wuerfeln.setObjectName("wuerfeln")
self.label = QtWidgets.QLabel(MenschUi)
self.label.setGeometry(QtCore.QRect(10, 450, 491, 21))
self.label.setText("")
self.label.setObjectName("label")
self.retranslateUi(MenschUi)
self.Abbrechen.accepted.connect(MenschUi.accept)
self.Abbrechen.rejected.connect(MenschUi.reject)
self.wuerfeln.clicked.connect(MenschUi.open)
QtCore.QMetaObject.connectSlotsByName(MenschUi)
def retranslateUi(self, MenschUi):
_translate = QtCore.QCoreApplication.translate
MenschUi.setWindowTitle(_translate("MenschUi", "Mensch Aergere dich Nicht!"))
self.Spieler.setText(_translate("MenschUi", "Spieler"))
self.Computer.setText(_translate("MenschUi", "Computer"))
self.wuerfeln.setText(_translate("MenschUi", "wuerfeln"))
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
Welcome = QtWidgets.QDialog()
ui = CLASS_WELCOME()
ui.setupUi(Welcome)
Welcome.show()
sys.exit(app.exec_())
Possibly calling self.hide() in the beginning of the method onOK would do the job. (Untested)
You could lookup some Methods here.