I'm trying to create a function in a register and login form using QLineEdit to show and hide password if click a QPushButton. I'm a beginner in Python, I'm just trying to do it but it's very hard... My attempt is not good because if I click the eye button the password is shown, but if click again to hide it does not work.
from PyQt5 import QtCore, QtGui, QtWidgets, uic
from PyQt5.QtWidgets import QPushButton, QLineEdit
import sys
import pymysql
pymysql.install_as_MySQLdb()
class MyWindow(QtWidgets.QMainWindow):
def __init__(self, maxWidth=None):
super(MyWindow, self).__init__()
uic.loadUi('MainWindow.ui', self)
self.eyepass_show()
self.eyepass_hide()
self.btn_show_pwd.clicked.connect(self.eyepass_hide)
self.btn_show_pwd.clicked.connect(self.eyepass_show)
def eyepass_show(self):
self.line_password.setEchoMode(QLineEdit.Normal)
print('show pass')
def eyepass_hide(self):
self.line_password.setEchoMode(QLineEdit.Password)
print('hide pass')
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = MyWindow()
window.show()
sys.exit(app.exec_())
form password hide/show eye:
is hiding password is show but if click again to hide not work
Instead of creating two separate methods as eyepass_show and eyepass_hide, you can create a single function and toggle the visibility. Also, you are trying to connect the same signal twice to two different methods by self.btn_show_pwd.clicked.connect(self.eyepass_hide)and self.btn_show_pwd.clicked.connect(self.eyepass_show)
Try something like this:
from PyQt5 import QtCore, QtGui, QtWidgets, uic
from PyQt5.QtWidgets import QPushButton, QLineEdit
import sys
import pymysql
pymysql.install_as_MySQLdb()
class MyWindow(QtWidgets.QMainWindow):
def __init__(self, maxWidth=None):
super(MyWindow, self).__init__()
uic.loadUi('MainWindow.ui', self)
self.eyepass_show()
self.eyepass_hide()
self.btn_show_pwd.clicked.connect(self.toggleVisibility)
def toggleVisibility(self):
if self.line_password.echoMode()==QLineEdit.Normal:
self.line_password.setEchoMode(QLineEdit.Password)
else:
self.line_password.setEchoMode(QLineEdit.Normal)
# self.btn_show_pwd.clicked.connect(self.eyepass_hide)
# self.btn_show_pwd.clicked.connect(self.eyepass_show)
#
# def eyepass_show(self):
# self.line_password.setEchoMode(QLineEdit.Normal)
# print('show pass')
#
# def eyepass_hide(self):
# self.line_password.setEchoMode(QLineEdit.Password)
# print('hide pass')
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = MyWindow()
window.show()
sys.exit(app.exec_())
Another possibility is to add a checkable QAction to the QLineEdit and connect to the toggled (or triggered) signal.
class MyWindow(QtWidgets.QMainWindow):
def __init__(self, maxWidth=None):
super(MyWindow, self).__init__()
uic.loadUi('MainWindow.ui', self)
icon = QtGui.QIcon('eye-icon.png')
self.showPassAction = QtWidgets.QAction(icon, 'Show password', self)
self.line_password.addAction(
self.showPassAction, QtWidgets.QLineEdit.TrailingPosition)
self.showPassAction.setCheckable(True)
self.showPassAction.toggled.connect(self.showPassword)
def showPassword(self, show):
self.line_password.setEchoMode(
QtWidgets.QLineEdit.Normal if show else QtWidgets.QLineEdit.Password)
If you want to show the password only when the mouse is pressed, then don't connect to the toggled signal, but find the child QToolButton for that action and connect to the pressed and released instead. In this case, the action doesn't need to be checkable.
self.line_password.addAction(
self.showPassAction, QtWidgets.QLineEdit.TrailingPosition)
showPassButton = self.line_password.findChild(QtWidgets.QAbstractButton)
showPassButton.pressed.connect(lambda: self.showPassword(True))
showPassButton.released.connect(lambda: self.showPassword(False))
One of the great things about PyQt5 is that it will automatically connect signals to methods for you. If you have a button named <mybutton> and a method in your app named on_<mybutton>_clicked, the the loadUi will automatically connect. So the pattern is
on_<widget_name>_<signal>
If we apply this to your problem, you should make your show/hide button a toggle button. In Qt Designer, set the checkable property to True (or do btn_show_pwd.clicked.setChecked(True))
The code:
from PyQt5 import QtCore, QtGui, QtWidgets, uic
from PyQt5.QtWidgets import QPushButton, QLineEdit
import sys
#import pymysql
#pymysql.install_as_MySQLdb()
class MyWindow(QtWidgets.QMainWindow):
def __init__(self, maxWidth=None):
super(MyWindow, self).__init__()
uic.loadUi('test1.ui', self)
self.line_password.setEchoMode(QLineEdit.Password)
def on_btn_show_pwd_toggled(self, checked):
if checked:
self.line_password.setEchoMode(QLineEdit.Password)
else:
self.line_password.setEchoMode(QLineEdit.Normal)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = MyWindow()
window.show()
sys.exit(app.exec_())
Related
I created a checkbox using PyQT, which normally works using mouse clicks.
I want to know if there is a way with which I can uncheck and check the checkbox using the program itself, and not a mouse click.
Basically I want to check and uncheck the box 10 times in 20 seconds and display it happening.
Here is my code for just the checkbox:
import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QLabel, QCheckBox, QWidget
from PyQt5.QtCore import QSize
class ExampleWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.setMinimumSize(QSize(140, 40))
self.setWindowTitle("Checkbox")
self.b = QCheckBox("Yes",self)
self.b.move(20,20)
self.b.resize(320,40)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
mainWin = ExampleWindow()
mainWin.show()
sys.exit( app.exec_() )
checked : bool
This property holds whether the button is checked
Only checkable buttons can be checked. By default, the button is unchecked.
The QTimer class provides repetitive and single-shot timers.
More ... https://doc.qt.io/qt-5/qtimer.html
import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QLabel, QCheckBox, QWidget
from PyQt5.QtCore import QSize
class ExampleWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.setMinimumSize(QSize(140, 40))
self.setWindowTitle("Checkbox")
self.b = QCheckBox("Yes",self)
self.b.move(20,20)
self.b.resize(320,40)
self.num = 0
self.timer = QtCore.QTimer()
self.timer.setInterval(2000) # msec
self.timer.timeout.connect(self.update_now)
self.timer.start()
def update_now(self):
self.b.setChecked(not self.b.isChecked()) # +++
self.num += 1
if self.num == 10: self.timer.stop()
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
mainWin = ExampleWindow()
mainWin.show()
sys.exit( app.exec_() )
I have two separate files, one that creates a system tray icon and context menu, and another a window to take user input.
traywindow.py contains this:
import sys
import os
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QWidget, QLabel, QLineEdit
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtCore import QSize
class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.setMinimumSize(QSize(320, 172))
self.setWindowTitle("Set Account")
# Setup username field
self.username_label = QLabel(self)
self.username_label.setText('Username')
self.username_field = QLineEdit(self)
self.username_label.move(45, 20)
self.username_field.move(115, 23)
self.username_field.resize(150, 25)
# Setup OK button
pybutton = QPushButton('OK', self)
pybutton.clicked.connect(self.buttonClicked)
pybutton.resize(100,32)
pybutton.move(110, 128)
def buttonClicked(self):
print('Username: ' + self.username_field.text())
def displayWindow():
app = QtWidgets.QApplication(sys.argv)
preferences_window = MainWindow()
preferences_window.show()
sys.exit(app.exec_())
if __name__ == "__main__":
displayWindow()
Which produces:
trayapp.py contains this:
import os
import sys
import traywindow
from PyQt5 import QtWidgets, QtCore, QtGui
class SystemTrayIcon(QtWidgets.QSystemTrayIcon):
def __init__(self, icon, parent=None):
QtWidgets.QSystemTrayIcon.__init__(self, icon, parent)
menu = QtWidgets.QMenu(parent)
prefs_action = menu.addAction('Preferences...')
self.setContextMenu(menu)
prefs_action.triggered.connect(self.setPrefs)
def setPrefs(self):
traywindow.displayWindow()
def main(image):
app = QtWidgets.QApplication(sys.argv)
w = QtWidgets.QWidget()
trayIcon = SystemTrayIcon(QtGui.QIcon(image), w)
trayIcon.show()
sys.exit(app.exec_())
if __name__ == '__main__':
icon = 'icon.png'
main(icon)
Which produces:
I want to launch the window from my context menu, so when I click on Preferences... it will open the Set Account window, and when I fill in the field and click on OK, capture that into variables/pass those along as arguments in the trayapp.py file. Currently, my attempt in the code above gives me this when I click on Preferences...:
Traceback (most recent call last):
File "/Users/Username/Downloads/trayapp.py", line 17, in setPrefs
traywindow.displayWindow()
File "/Users/Username/Downloads/traywindow.py", line 36, in displayWindow
sys.exit(app.exec_())
SystemExit: -1
[Finished in 3.0s with exit code -6]
I'm new to PyQt5 and feel like I'm missing something fundamental. From the error I think it's to do with how each file is called at the end to produce its UI, but I haven't found an answer in the docs so far.
You can only have one QApplication and in displayWindow you are creating a second QApplication, instead create a MainWindow and do not call displayWindow.
def setPrefs(self):
self.window = traywindow.MainWindow()
self.window.show()
I have multiple windows in a Python GUI application using PyQt5.
I need to hide current window when a button is clicked and show the next window.
This works fine from WindowA to WindowB but I get an error while going from WindowB to WindowC.
I know there is some problem in initialization as the initialization code in WindowB is unreachable, but being a beginner with PyQt, i can't figure out the solution.
WindowA code:
from PyQt5 import QtCore, QtGui, QtWidgets
from WindowB import Ui_forWindowB
class Ui_forWindowA(object):
def setupUi(self, WindowA):
# GUI specifications statements here
self.someButton = QtWidgets.QPushButton(self.centralwidget)
self.someButton.clicked.connect(self.OpenWindowB)
# More GUI specifications statements here
def retranslateUi(self, WindowA):
# More statements here
def OpenWindowB(self):
self.window = QtWidgets.QMainWindow()
self.ui = Ui_forWindowB()
self.ui.setupUi(self.window)
WindowA.hide()
self.window.show()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
WindowA = QtWidgets.QMainWindow()
ui = Ui_forWindowA()
ui.setupUi(WindowA)
MainWindow.show()
sys.exit(app.exec_())
WindowB code:
from PyQt5 import QtCore, QtGui, QtWidgets
from WindowB import Ui_forWindowB
class Ui_forWindowB(object):
def setupUi(self, WindowB):
# GUI specifications statements here
self.someButton = QtWidgets.QPushButton(self.centralwidget)
self.someButton.clicked.connect(self.OpenWindowC)
# More GUI specifications statements here
def retranslateUi(self, WindowB):
# More statements here
def OpenWindowB(self):
self.window = QtWidgets.QMainWindow()
self.ui = Ui_forWindowC()
self.ui.setupUi(self.window)
WindowB.hide() # Error here
self.window.show()
# The below code doesn't get executed when Ui_forWindowB is called from A
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
WindowB = QtWidgets.QMainWindow()
ui = Ui_forWindowB()
ui.setupUi(WindowB)
MainWindow.show()
sys.exit(app.exec_())
It works fine from A to B where
WindowA.hide() # Works Properly
While calling WindowC from WindowB
WindowB.hide() # Shows error: name 'WindowB' is not defined
I understand that the initialization isn't done as the "if" statement doesn't get executed.
How to get this working?
I have many more windows to connect in this flow
When you run a Python script, the first file executed will be assigned the name __main__, therefore, if you first execute WindowA the code inside the block if __name__ == "__main__" gets executed and the application is started using WindowA as the main window, similarly if you execute your WindowB script first, the application will be started usingWindowB as the main window.
You cannot start two applications within the same process so you have to choose which one you want to be the main window, all the others will be secondary windows (even if they inherit from QMainWindow).
Nevertheless, you should be able to instantiate new windows from a method in your main window.
As a good practice, you could create a main script to handle the initialization of your application and start an empty main window that will then handle your workflow, also, you may want to wrap your UI classes, specially if they are generated using Qt creator, here is an example:
main.py
import PyQt5
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QApplication
from views.main_window import MainWindow
class App(QApplication):
"""Main application wrapper, loads and shows the main window"""
def __init__(self, sys_argv):
super().__init__(sys_argv)
# Show main window
self.main_window = MainWindow()
self.main_window.show()
if __name__ == '__main__':
app = App(sys.argv)
sys.exit(app.exec_())
main_window.py
This is the main window, it doesn't do anything, just control the workflow of the application, i.e. load WindowA, then WindowB etc., notice that I inherit from Ui_MainWindow, by doing so, you can separate the look and feel from the logic and use Qt Creator to generate your UI:
from PyQt5.QtWidgets import QWidget, QMainWindow
from views.window_a import WindowA
from views.window_b import WindowB
from widgets.main_window import Ui_MainWindow
class MainWindow(Ui_MainWindow, QMainWindow):
"""Main application window, handles the workflow of secondary windows"""
def __init__(self):
Ui_MainWindow.__init__(self)
QMainWindow.__init__(self)
self.setupUi(self)
# start hidden
self.hide()
# show window A
self.window_a = WindowA()
self.window_a.actionExit.triggered.connect(self.window_a_closed)
self.window_a.show()
def window_a_closed(self):
# Show window B
self.window_b = WindowB()
self.window_b.actionExit.triggered.connect(self.window_b_closed)
self.window_b.show()
def window_b_closed(self):
#Close the application if window B is closed
self.close()
window_a.py
from PyQt5.QtWidgets import QWidget, QMainWindow
from widgets.main_window import Ui_forWindowA
class WindowA(Ui_forWindowA, QMainWindow):
"""Window A"""
def __init__(self):
Ui_forWindowA.__init__(self)
QMainWindow.__init__(self)
self.setupUi(self)
# Do some stuff
window_b.py
from PyQt5.QtWidgets import QWidget, QMainWindow
from widgets.main_window import Ui_forWindowB
class WindowA(Ui_forWindowB, QMainWindow):
"""Window B"""
def __init__(self):
Ui_forWindowB.__init__(self)
QMainWindow.__init__(self)
self.setupUi(self)
# Do some stuff
Hopefully should give you an idea to get you going.
I was writing a pyqt5 program for expression evaluator but after running the program i am not able to see any widgets and getting blank window
def expressionevaluator():
import sys
from PyQt5 import QtWidgets
from PyQt5 import QtCore
from PyQt5 import QtGui
from PyQt5.QtWidgets import QApplication, QWidget,QMainWindow
class Window(QtWidgets.QMainWindow):
def __init__(self):
super(Window,self).__init__()
self.setGeometry(50,50,500,300)
self.setWindowTitle("PyQt Tutorial")
self.setWindowIcon=QtGui.QIcon('pyqt_example2.PNG')
self.home()
def ExitForm(self):
sys.exit()
def home(self):
vbox=QtWidgets.QVBoxLayout()
textbrowser=QtWidgets.QTextBrowser()
lineedit=QtWidgets.QLineEdit()
btn=QtWidgets.QPushButton("QUIT")
btn.clicked.connect(self.close)
vbox.addWidget(textbrowser)
vbox.addWidget(lineedit)
vbox.addWidget(btn)
self.setLayout(vbox)
self.show()
if __name__=="__main__":
app=QApplication(sys.argv)
GUI=Window()
sys.exit(app.exec_())
expressionevaluator()
So what should I do ?
Just running your code I got a widget showing up in my screen, but its components didn't show up. Instead of setting a layout of a QMainWindow try to have a central widget (QWidget) set its layout with its components than set the QMainWindow central widget with this widget. There you go, now you have all working fine.
You had problems with the layout because QMainWindow behaves differently from others Widgets, it has its own layout and many other default behaviors, central widget is the reason why nothing was showing up inside your main window.
def expressionevaluator():
import sys
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QLineEdit
from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtWidgets import QTextBrowser
from PyQt5.QtWidgets import QVBoxLayout
from PyQt5.QtWidgets import QWidget
class Window(QMainWindow):
def __init__(self):
super(Window,self).__init__()
self.setGeometry(50,50,500,300)
self.setWindowTitle("PyQt Tutorial")
self.setWindowIcon = QIcon('pyqt_example2.PNG')
self.home()
def ExitForm(self):
sys.exit()
def home(self):
vbox = QVBoxLayout()
textbrowser = QTextBrowser()
lineedit = QLineEdit()
btn = QPushButton("QUIT")
central_widget = QWidget()
central_widget.setLayout(vbox)
btn.clicked.connect(self.close)
vbox.addWidget(textbrowser)
vbox.addWidget(lineedit)
vbox.addWidget(btn)
self.setCentralWidget(central_widget)
self.show()
if __name__=="__main__":
app = QApplication(sys.argv)
GUI = Window()
GUI.show()
sys.exit(app.exec_())
expressionevaluator()
Note: There are many improvements in the structure of your code you could do, I just changed as less as I could to make it work, for example try to not import all the modules at once, import just what you need for example QIcon, QLineEdit and so on, instead of the whole QtWidgets, or QtCore...
Following code works well:
import sys
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QLineEdit
from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtWidgets import QTextBrowser
from PyQt5.QtWidgets import QVBoxLayout
from PyQt5.QtWidgets import QWidget
class Window(QMainWindow):
def __init__(self):
super(Window,self).__init__()
self.setGeometry(50,50,500,300)
self.setWindowTitle("PyQt Tutorial")
self.setWindowIcon = QIcon('pyqt_example2.PNG')
self.home()
def ExitForm(self):
sys.exit()
def home(self):
vbox = QVBoxLayout()
textbrowser = QTextBrowser()
lineedit = QLineEdit()
btn = QPushButton("QUIT")
central_widget = QWidget()
central_widget.setLayout(vbox)
btn.clicked.connect(self.ExitForm)
vbox.addWidget(textbrowser)
vbox.addWidget(lineedit)
vbox.addWidget(btn)
self.setCentralWidget(central_widget)
self.show()
if __name__=="__main__":
app = QApplication(sys.argv)
GUI = Window()
GUI.show()
sys.exit(app.exec_())
I want to add startup window that when I click button, it will open another window and close current window. For each window, it has seperated UI which created from Qt Designer in .ui form.
I load both .ui file via uic.loadUiType(). The first window(first UI) can normally show its UI but when I click button to go to another window, another UI (second UI) doesn't work. It likes open blank window.
Another problem is if I load first UI and then change to second UI (delete that Class and change to another Class, also delete uic.loadUiType()), the second UI still doesn't work (show blank window)
Please help... I research before create this question but can't find the answer.
Here's my code. How can I fix it?
import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QIcon
from PyQt5 import uic
#load both ui file
uifile_1 = 'UI/openPage.ui'
form_1, base_1 = uic.loadUiType(uifile_1)
uifile_2 = 'UI/mainPage.ui'
form_2, base_2 = uic.loadUiType(uifile_2)
class Example(base_1, form_1):
def __init__(self):
super(base_1,self).__init__()
self.setupUi(self)
self.startButton.clicked.connect(self.change)
def change(self):
self.main = MainPage()
self.main.show()
class MainPage(base_2, form_2):
def __int__(self):
super(base_2, self).__init__()
self.setupUi(self)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())
First you have an error, you must change __int__ to __init__. To close the window call the close() method.
import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QIcon
from PyQt5 import uic
#load both ui file
uifile_1 = 'UI/openPage.ui'
form_1, base_1 = uic.loadUiType(uifile_1)
uifile_2 = 'UI/mainPage.ui'
form_2, base_2 = uic.loadUiType(uifile_2)
class Example(base_1, form_1):
def __init__(self):
super(base_1,self).__init__()
self.setupUi(self)
self.startButton.clicked.connect(self.change)
def change(self):
self.main = MainPage()
self.main.show()
self.close()
class MainPage(base_2, form_2):
def __init__(self):
super(base_2, self).__init__()
self.setupUi(self)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())