Detect when "X" button is clicked - python

I have created a login window where the window will remain until the user enters the right password, and if the user presses the "X" button on the top right corner, the window should disappear. However, the window disappears even if the user enters the incorrect password.
Code:
class Login(QDialog):
def __init__(self,parent=None):
super(Login, self).__init__(parent)
self.grid = QGridLayout(self)
self.setGeometry(650, 350, 400, 150)
self.setFixedSize(400, 150)
self.UserLabels = QLabel(self)
self.UserLabels.setText('Login Number:')
self.grid.addWidget(self.UserLabels, 0, 0, 1, 1)
self.textName = QLineEdit(self)
self.grid.addWidget(self.textName, 0, 1, 1, 2)
self.buttonLogin = QPushButton('Submit', self)
self.buttonLogin.clicked.connect(self.closeGUI)
self.grid.addWidget(self.buttonLogin, 2, 0, 1, 3)
finish = QAction("Quit", self)
finish.triggered.connect(self.closeWin)
def closeGUI(self):
self.close()
return str(self.textName.text())
def closeWin(self):
self.close()
return 1
def handleLogin():
flag = 0
while flag == 0:
edit_params__QD = Login()
edit_params__QD.exec_()
if edit_params__QD.result() == 0:
password = edit_params__QD.closeGUI()
if password == '6':
flag = 1
else:
flag = 0
if edit_params__QD.closeWin() == 1:
flag = 1
if __name__ == '__main__':
app = QApplication(sys.argv)
handleLogin()

Try it:
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
class MainWindow(QMainWindow):
windowList = []
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setWindowTitle('Main interface')
self.showMaximized()
# Create Menu Bar
self.createMenus()
def createMenus(self):
# Create login action
self.printAction1 = QAction(self.tr("Entrance"), self)
self.printAction1.triggered.connect(self.on_printAction1_triggered)
# Create exit action
self.printAction2 = QAction(self.tr("Exit"), self)
self.printAction2.triggered.connect(self.on_printAction2_triggered)
# Create menu, add actions
self.printMenu = self.menuBar().addMenu(self.tr("Entrance and Exit"))
self.printMenu.addAction(self.printAction1)
self.printMenu.addAction(self.printAction2)
# Step 1: Login
def on_printAction1_triggered(self):
self.close()
dialog = LoginDialog()
if dialog.exec_()==QDialog.Accepted:
the_window = MainWindow()
self.windowList.append(the_window) # ! It is important !
the_window.show()
def on_printAction2_triggered(self):
self.close()
# Interface close event
def closeEvent(self, event):
print("The End")
class LoginDialog(QDialog):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setWindowTitle('Login interface')
self.resize(250, 200)
self.setFixedSize(self.width(), self.height())
self.setWindowFlags(Qt.WindowCloseButtonHint)
# Configure UI controls
self.frame = QFrame(self)
self.frame.resize(250, 200)
self.verticalLayout = QVBoxLayout(self.frame)
self.lineEdit_account = QLineEdit()
self.lineEdit_account.setPlaceholderText("Please enter nickName (admin)")
self.verticalLayout.addWidget(self.lineEdit_account)
self.lineEdit_password = QLineEdit()
self.lineEdit_password.setPlaceholderText("Please enter your password (admin)")
self.verticalLayout.addWidget(self.lineEdit_password)
self.pushButton_enter = QPushButton()
self.pushButton_enter.setText("OK")
self.verticalLayout.addWidget(self.pushButton_enter)
self.pushButton_quit = QPushButton()
self.pushButton_quit.setText("Cancel")
self.verticalLayout.addWidget(self.pushButton_quit)
# bindings button Event
self.pushButton_enter.clicked.connect(self.on_pushButton_enter_clicked)
self.pushButton_quit.clicked.connect(QCoreApplication.instance().quit)
def on_pushButton_enter_clicked(self):
# Check nickName
if self.lineEdit_account.text() != "admin":
return
# Check password
if self.lineEdit_password.text() != "admin":
return
# Close the dialog and return 1 when checking
self.accept()
if __name__ == "__main__":
app = QApplication(sys.argv)
dialog = LoginDialog()
if dialog.exec_()==QDialog.Accepted:
the_window = MainWindow()
the_window.show()
sys.exit(app.exec_())

A more complete example showing how to write a login dialog is given here:
Login dialog PyQt
However, in your own example, you should note that It's not necessary to handle the close-event, because the "X" button will automatically
set the dialog's result to Rejected. Instead, you just need to set the result to Accepted when the submit button is clicked. You can then check the return value of exec_() to see what the user did.
Here is a re-write of your script that does that:
import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
class Login(QDialog):
def __init__(self,parent=None):
super(Login, self).__init__(parent)
self.grid = QGridLayout(self)
self.setGeometry(650, 350, 400, 150)
self.setFixedSize(400, 150)
self.UserLabels = QLabel(self)
self.UserLabels.setText('Login Number:')
self.grid.addWidget(self.UserLabels, 0, 0, 1, 1)
self.textName = QLineEdit(self)
self.grid.addWidget(self.textName, 0, 1, 1, 2)
self.buttonLogin = QPushButton('Submit', self)
self.buttonLogin.clicked.connect(self.accept)
self.grid.addWidget(self.buttonLogin, 2, 0, 1, 3)
def password(self):
return self.textName.text()
def handleLogin():
result = None
login = Login()
while result is None:
if login.exec_() == QDialog.Accepted:
password = login.password()
if password == '6':
result = True
else:
result = False
return result
if __name__ == '__main__':
app = QApplication(sys.argv)
if handleLogin():
print('logged in')
else:
print('cancelled')

Related

QListWidget, rename items with user input

I have contextmenu to a listWidget with delete and rename item. For delete, I used RemoveRow. But, I can't rename with user-input. How can I replace this line item.setText('new_name') by an action allow my change name by user
import sys
from PyQt5 import QtCore, QtWidgets
class Dialog(QtWidgets.QDialog):
def __init__(self, parent=None):
super(Dialog, self).__init__()
self.listWidget = QtWidgets.QListWidget()
self.listWidget.addItems('apple orange lemon'.split())
self.listWidget.installEventFilter(self)
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.listWidget)
def eventFilter(self, source, event):
if (event.type() == QtCore.QEvent.ContextMenu and
source is self.listWidget):
menu = QtWidgets.QMenu()
Delete = menu.addAction('Delete')
Rename = menu.addAction('Rename')
#action = menu.exec_(event.globalPos())
action = menu.exec_(self.mapToGlobal(event.pos())) #when inside self
if action == Delete:
item = source.itemAt(event.pos())
source.model().removeRow(source.currentRow())
elif action == Rename:
item = source.itemAt(event.pos())
#
item.setText('new')
"How can I rename by user input, not by setText??"
return True
return super(Dialog, self).eventFilter(source, event)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = Dialog()
window.setGeometry(600, 100, 300, 200)
window.show()
sys.exit(app.exec_())
You can use QInputDialog.getText() to ask for new text and use it with setText().
elif action == Rename:
text, okPressed = QtWidgets.QInputDialog.getText(self, "New name","New name:")
if okPressed and text != '':
item = source.itemAt(event.pos())
item.setText(text)
You can even copy text from list to QInputDialog so user can edit it.
elif action == Rename:
item = source.itemAt(event.pos())
text, okPressed = QtWidgets.QInputDialog.getText(self, "New name","New name:", text=item.text())
if okPressed and text != '':
item.setText(text)
Full working code
import sys
from PyQt5 import QtCore, QtWidgets
class Dialog(QtWidgets.QDialog):
def __init__(self, parent=None):
super(Dialog, self).__init__()
self.listWidget = QtWidgets.QListWidget()
self.listWidget.addItems('apple orange lemon'.split())
self.listWidget.installEventFilter(self)
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.listWidget)
def eventFilter(self, source, event):
if (event.type() == QtCore.QEvent.ContextMenu and
source is self.listWidget):
menu = QtWidgets.QMenu()
Delete = menu.addAction('Delete')
Rename = menu.addAction('Rename')
#action = menu.exec_(event.globalPos())
action = menu.exec_(self.mapToGlobal(event.pos())) #when inside self
if action == Delete:
item = source.itemAt(event.pos())
source.model().removeRow(source.currentRow())
elif action == Rename:
item = source.itemAt(event.pos())
text, okPressed = QtWidgets.QInputDialog.getText(self, "New name","New name:", text=item.text())
if okPressed and text != '':
item.setText(text)
return True
return super(Dialog, self).eventFilter(source, event)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = Dialog()
window.setGeometry(600, 100, 300, 200)
window.show()
sys.exit(app.exec_())

pyqt5 in not responding state when calling the url

i just implemented a login in pyqt but in between the calling the url and getting the response the qt window is showing the not responding state
can anyone please suggest me how to avoid not responding state
code:
class Login(QDialog):
def __init__(self, height, width, parent=None):
super(Login, self).__init__(parent)
self.resize(300, 300)
size = self.geometry()
self.move((width-size.width())/2, (height-size.height())/2)
username = QLabel("Username", self)
username.move(100, 35)
self.textName = QLineEdit(self)
password = QLabel("Password", self)
password.move(100, 110)
self.textPass = QLineEdit(self)
self.textPass.setEchoMode(QLineEdit.Password)
self.buttonLogin = QPushButton('Login', self)
self.buttonLogin.clicked.connect(self.handleLogin)
layout = QVBoxLayout(self)
layout.addWidget(self.textName)
layout.addWidget(self.textPass)
layout.addWidget(self.buttonLogin)
def handleLogin(self):
# TODO: Connect to flask application to check login credentials
payload = {"username":self.textName.text(),"password":self.textPass.text()}
print("payload:", payload)
r = requests.post("http://127.0.0.1:5000/login",data=payload)
print(r.content.decode("utf-8"))
if r.status_code == 200:
self.accept()
else:
QMessageBox.warning(self, 'Error', 'Bad user or password')
1. Use threads: Tasks that consume a lot of time must be executed in another thread
import requests
from PyQt5 import QtCore, QtWidgets
class LoginWorker(QtCore.QObject):
logged = QtCore.pyqtSignal(bool)
def setCredentials(self, username, password):
self.payload = {"username": username, "password": password}
#QtCore.pyqtSlot()
def login(self):
print("payload:", self.payload)
r = requests.post("http://127.0.0.1:5000/login",data=self.payload)
print(r.content.decode("utf-8"))
status = r.status_code == 200
self.logged.emit(status)
class Login(QtWidgets.QDialog):
def __init__(self, height, width, parent=None):
super(Login, self).__init__(parent)
self.resize(300, 300)
size = self.geometry()
self.move((width-size.width())/2, (height-size.height())/2)
username = QtWidgets.QLabel("Username")
self.textName = QtWidgets.QLineEdit()
password = QtWidgets.QLabel("Password")
self.textPass = QtWidgets.QLineEdit()
self.textPass.setEchoMode(QtWidgets.QLineEdit.Password)
self.buttonLogin = QtWidgets.QPushButton('Login')
self.buttonLogin.clicked.connect(self.handleLogin)
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(username, alignment=QtCore.Qt.AlignCenter)
layout.addWidget(self.textName)
layout.addWidget(password, alignment=QtCore.Qt.AlignCenter)
layout.addWidget(self.textPass)
layout.addWidget(self.buttonLogin)
layout.addStretch()
thread = QtCore.QThread(self)
thread.start()
self.login_worker = LoginWorker()
self.login_worker.moveToThread(thread)
self.login_worker.logged.connect(self.onLogged)
def handleLogin(self):
# TODO: Connect to flask application to check login credentials
self.login_worker.setCredentials(self.textName.text(), self.textPass.text())
QtCore.QTimer.singleShot(0, self.login_worker.login)
def onLogged(self, status):
if status:
self.accept()
else:
QtWidgets.QMessageBox.warning(self, 'Error', 'Bad user or password')
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = Login(100, 100)
w.show()
sys.exit(app.exec_())
2. Use QNAM:
from PyQt5 import QtCore, QtWidgets, QtNetwork
class Login(QtWidgets.QDialog):
def __init__(self, height, width, parent=None):
super(Login, self).__init__(parent)
self.resize(300, 300)
size = self.geometry()
self.move((width-size.width())/2, (height-size.height())/2)
username = QtWidgets.QLabel("Username")
self.textName = QtWidgets.QLineEdit()
password = QtWidgets.QLabel("Password")
self.textPass = QtWidgets.QLineEdit()
self.textPass.setEchoMode(QtWidgets.QLineEdit.Password)
self.buttonLogin = QtWidgets.QPushButton('Login')
self.buttonLogin.clicked.connect(self.handleLogin)
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(username, alignment=QtCore.Qt.AlignCenter)
layout.addWidget(self.textName)
layout.addWidget(password, alignment=QtCore.Qt.AlignCenter)
layout.addWidget(self.textPass)
layout.addWidget(self.buttonLogin)
layout.addStretch()
def handleLogin(self):
# TODO: Connect to flask application to check login credentials
postData = QtCore.QUrlQuery()
postData.addQueryItem("username", self.textName.text())
postData.addQueryItem("password", self.textPass.text())
qnam = QtNetwork.QNetworkAccessManager()
url = "http://127.0.0.1:5000/home"
reply = qnam.post(QtNetwork.QNetworkRequest(QtCore.QUrl(url)), postData.toString(QtCore.QUrl.FullyEncoded).encode())
loop = QtCore.QEventLoop()
reply.finished.connect(loop.quit)
loop.exec_()
code = reply.attribute(QtNetwork.QNetworkRequest.HttpStatusCodeAttribute)
if code == 200:
self.accept()
else:
QtWidgets.QMessageBox.warning(self, 'Error', 'Bad user or password')
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = Login(100, 100)
w.show()
sys.exit(app.exec_())

location permission popup

I'm making a web browser in PyQt5 and Python. How to make location permission popup like the following:
Here is my code:
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtWebEngineWidgets import *
from PyQt5 import QtCore, QtGui, QtWidgets, QtWebEngineWidgets,QtWebEngine
from PyQt5.QtPrintSupport import *
import os
import sys
from time import sleep
from threading import Timer
import re
import urllib.request
class SearchPanel(QtWidgets.QWidget):
searched = QtCore.pyqtSignal(str, QtWebEngineWidgets.QWebEnginePage.FindFlag)
closed = QtCore.pyqtSignal()
def __init__(self, parent=None):
super(SearchPanel, self).__init__(parent)
lay = QtWidgets.QHBoxLayout(self)
self.case_button = QtWidgets.QPushButton('Match &Case', checkable=True)
next_button = QtWidgets.QPushButton('&Next')
prev_button = QtWidgets.QPushButton('&Previous')
self.search_le = QtWidgets.QLineEdit()
self.setFocusProxy(self.search_le)
next_button.clicked.connect(self.update_searching)
prev_button.clicked.connect(self.on_preview_find)
self.case_button.clicked.connect(self.update_searching)
for btn in (self.case_button, self.search_le, next_button, prev_button, ):
lay.addWidget(btn)
if isinstance(btn, QtWidgets.QPushButton): btn.clicked.connect(self.setFocus)
self.search_le.textChanged.connect(self.update_searching)
self.search_le.returnPressed.connect(self.update_searching)
self.closed.connect(self.search_le.clear)
QtWidgets.QShortcut(QtGui.QKeySequence.FindNext, self, activated=next_button.animateClick)
QtWidgets.QShortcut(QtGui.QKeySequence.FindPrevious, self, activated=prev_button.animateClick)
QtWidgets.QShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Escape), self.search_le, activated=self.closed)
#QtCore.pyqtSlot()
def on_preview_find(self):
self.update_searching(QtWebEngineWidgets.QWebEnginePage.FindBackward)
#QtCore.pyqtSlot()
def update_searching(self, direction=QtWebEngineWidgets.QWebEnginePage.FindFlag()):
flag = direction
if self.case_button.isChecked():
flag |= QtWebEngineWidgets.QWebEnginePage.FindCaseSensitively
self.searched.emit(self.search_le.text(), flag)
def showEvent(self, event):
super(SearchPanel, self).showEvent(event)
self.setFocus(True)
class AboutDialog(QDialog):
def __init__(self, *args, **kwargs):
super(AboutDialog, self).__init__(*args, **kwargs)
QBtn = QDialogButtonBox.Ok # No cancel
self.buttonBox = QDialogButtonBox(QBtn)
self.buttonBox.accepted.connect(self.accept)
self.buttonBox.rejected.connect(self.reject)
layout = QVBoxLayout()
title = QLabel("Pyxis Browser")
font = title.font()
font.setPointSize(20)
title.setFont(font)
layout.addWidget(title)
logo = QLabel()
logo.setPixmap(QPixmap(os.path.join('', 'ma-icon-128.png')))
layout.addWidget(logo)
layout.addWidget(QLabel("Version 1.0.0"))
layout.addWidget(QLabel("Copyright."))
for i in range(0, layout.count()):
layout.itemAt(i).setAlignment(Qt.AlignHCenter)
layout.addWidget(self.buttonBox)
self.setLayout(layout)
class MyPage(QWebEnginePage):
def __init__(self, *args, **kwargs):
super(MyPage, self).__init__(*args, **kwargs)
def triggerAction(self, action, checked=False):
if action == QWebEnginePage.OpenLinkInNewWindow:
self.createWindow(QWebEnginePage.WebBrowserWindow)
return super(MyPage, self).triggerAction(action, checked)
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.browser = QWebEngineView()
self.browser.setUrl(QUrl("https://androidd.pw/Login/"))
QWebEnginePage.JavascriptCanOpenWindows:True
self.browser.urlChanged.connect(self.update_urlbar)
self.browser.urlChanged.connect(self.page_loading)
self.browser.loadFinished.connect(self.update_title)
self.setCentralWidget(self.browser)
self.status = QStatusBar()
self.setStatusBar(self.status)
self.setCentralWidget(self.browser)
#self.browser.page().settings().setAttribute(QWebEngineSettings.AllowGeolocationOnInsecureOrigins, True)
navtb = QToolBar("Navigation")
navtb.setIconSize(QSize(16, 16))
self.addToolBar(navtb)
guide = QToolBar("Navigation")
guide.setIconSize(QSize(16, 16))
self.addToolBar(guide)
self.guidestate = QLabel() # Yes, really!
self.guidestate.setText('Welcome to Pyxis Ad')
font = self.guidestate.font()
font.setPointSize(14)
self.guidestate.setFont(font)
guide.addWidget(self.guidestate)
self.done_btn = QAction(QIcon(os.path.join('', 'done.png')), "Done", self)
self.done_btn.setVisible(False)
self.done_btn.triggered.connect(self.start_earning)
guide.addAction(self.done_btn)
self.child_domain = QAction(QIcon(os.path.join('', 'new_ad.png')), "Load New Pyxis Domain", self)
self.child_domain.setVisible(False)
self.child_domain.triggered.connect(self.load_child_domain)
guide.addAction(self.child_domain)
self.advertise = QAction(QIcon(os.path.join('', 'new_ad.png')), "Load New Avertisements Site", self)
self.advertise.setVisible(False)
self.advertise.triggered.connect(self.load_advertise)
guide.addAction(self.advertise)
self.load_new_url = QAction(QIcon(os.path.join('', 'new_ad.png')), "Reload New Site", self)
self.load_new_url.setVisible(False)
self.load_new_url.triggered.connect(self.new_ad_site)
guide.addAction(self.load_new_url)
back_btn = QAction(QIcon(os.path.join('', 'arrow-180.png')), "Back", self)
back_btn.setStatusTip("Back to previous page")
back_btn.triggered.connect(self.browser.back)
navtb.addAction(back_btn)
next_btn = QAction(QIcon(os.path.join('', 'arrow-000.png')), "Forward", self)
next_btn.setStatusTip("Forward to next page")
next_btn.triggered.connect(self.browser.forward)
navtb.addAction(next_btn)
reload_btn = QAction(QIcon(os.path.join('', 'arrow-circle-315.png')), "Reload", self)
reload_btn.setStatusTip("Reload page")
reload_btn.triggered.connect(self.browser.reload)
navtb.addAction(reload_btn)
home_btn = QAction(QIcon(os.path.join('', 'home.png')), "Home", self)
home_btn.setStatusTip("Go home")
home_btn.triggered.connect(self.navigate_home)
navtb.addAction(home_btn)
navtb.addSeparator()
self.httpsicon = QLabel() # Yes, really!
self.httpsicon.setPixmap(QPixmap(os.path.join('', 'lock-nossl.png')))
navtb.addWidget(self.httpsicon)
self.urlbar = QLineEdit()
#self.urlbar.setDisabled(1)
self.urlbar.returnPressed.connect(self.navigate_to_url)
navtb.addWidget(self.urlbar)
QWebEnginePage.JavascriptCanOpenWindows:True
stop_btn = QAction(QIcon(os.path.join('', 'cross-circle.png')), "Stop", self)
stop_btn.setStatusTip("Stop loading current page")
stop_btn.triggered.connect(self.browser.stop)
navtb.addAction(stop_btn)
help_menu = self.menuBar().addMenu("&Help")
about_action = QAction(QIcon(os.path.join('', 'question.png')), "About Browser", self)
about_action.setStatusTip("Find out more about Pyxis Browser") # Hungry!
about_action.triggered.connect(self.about)
help_menu.addAction(about_action)
navigate_mozarella_action = QAction(QIcon(os.path.join('', 'lifebuoy.png')), "Pyxis Homepage", self)
navigate_mozarella_action.setStatusTip("Go to Browser Homepage")
navigate_mozarella_action.triggered.connect(self.navigate_mozarella)
help_menu.addAction(navigate_mozarella_action)
self.setWindowIcon(QIcon(os.path.join('', 'ma-icon-64.png')))
def update_title(self):
title = self.browser.page().title()
self.setWindowTitle("%s - Pyxis" % title)
def page_loading(self):
title = 'Loading...'
self.setWindowTitle("%s - Pyxis" % title)
def navigate_mozarella(self):
self.browser.setUrl(QUrl("http://androidd.pw"))
def about(self):
dlg = AboutDialog()
dlg.exec_()
def print_page(self):
dlg = QPrintPreviewDialog()
dlg.paintRequested.connect(self.browser.print_)
dlg.exec_()
def navigate_home(self):
self.browser.setUrl(QUrl("http://androidd.pw"))
def start_earning(self):
self.browser.setUrl(QUrl("http://androidd.pw/API/legal_click"))
def load_child_domain(self):
self.browser.setUrl(QUrl('https://androidd.pw/API/getRandom/general'))
def load_advertise(self):
self.browser.setUrl(QUrl('https://androidd.pw/API/getRandom/ads'))
def navigate_to_url(self): # Does not receive the Url
q = QUrl(self.urlbar.text())
if q.scheme() == "":
q.setScheme("http")
self.browser.setUrl(q)
def timeout(self):
self.guidestate.setText('Ad Completed')
self.done_btn.setVisible(True)
self.load_new_url.setVisible(False)
def new_ad_site(self):
with urllib.request.urlopen("http://androidd.pw/API/single_site") as single_url:single = single_url.read()
self.browser.setUrl(QUrl(single.decode('utf-8')))
def update_urlbar(self, q):
###################################################################################
url = q.host()
#http://ipackersmovers.com/API/url/general?url=http://www.firsttecnology.us
with urllib.request.urlopen("http://androidd.pw/API/url/general?url="+url) as pyxis_url:pyxis = pyxis_url.read()
with urllib.request.urlopen("http://androidd.pw/API/url/ads?url="+url) as dom_url:ad = dom_url.read()
#with urllib.request.urlopen("http://androidd.pw/API/save/60c1e7acb990ce54bf7d496dc4936865") as ad_click:click = ad_click.read()
if pyxis == b'0':
pyxis = False
else:
pyxis = True
if ad == b'0':
ad = False
else:
ad = True
if pyxis:
self.guidestate.setText('Welcome to Pyxis Ad | You are currently on working area')
self.done_btn.setVisible(False)
self.load_new_url.setVisible(False)
self.child_domain.setVisible(False)
self.advertise.setVisible(False)
elif ad:
self.guidestate.setText('Click On Adsense Ad | if Ads are not visible then Reload new site =>')
self.done_btn.setVisible(False)
self.load_new_url.setVisible(True)
self.child_domain.setVisible(False)
self.advertise.setVisible(False)
elif q.host() == 'www.google.com' or q.host() == 'google.com':
query_url = q.query()
if re.search("^q=.*&gws_rd=ssl$", query_url):
highlighting = query_url[2:-11]
else:
highlighting = query_url[2:]
with urllib.request.urlopen("http://androidd.pw/API/url/general?url="+highlighting) as pyxis_url:pyxis_child = pyxis_url.read()
with urllib.request.urlopen("http://androidd.pw/API/url/ads?url="+highlighting) as dom_url:advert = dom_url.read()
self.guidestate.setText('Please Click on the first link from search results | Reload For New =>')
if pyxis_child.decode('utf-8'):
self.child_domain.setVisible(True)
elif advert.decode('utf-8'):
self.advertise.setVisible(True)
self.done_btn.setVisible(False)
self.load_new_url.setVisible(False)
direction=QtWebEngineWidgets.QWebEnginePage.FindFlag()
self.browser.findText(highlighting, direction)
else:
self.guidestate.setText('Please wait...')
self.done_btn.setVisible(False)
self.load_new_url.setVisible(False)
self.child_domain.setVisible(False)
self.advertise.setVisible(False)
# duration is in seconds
t = Timer(25, self.timeout)
t.start()
############################Checking which site is on###############################
if q.scheme() == 'https':
# Secure padlock icon
self.httpsicon.setPixmap(QPixmap(os.path.join('images', 'lock-ssl.png')))
else:
# Insecure padlock icon
self.httpsicon.setPixmap(QPixmap(os.path.join('images', 'lock-nossl.png')))
self.urlbar.setText(q.toString())
self.urlbar.setCursorPosition(0)
def createWindow(self, windowType):
if windowType == QWebEnginePage.WebBrowserTab:
self.browser = MainWindow()
self.browser.setAttribute(Qt.WA_DeleteOnClose, True)
self.browser.show()
return self.browser
return super(MainWindow, self).createWindow(windowType)
if __name__ == '__main__':
app = QApplication(sys.argv)
app.setApplicationName("Pyxis")
app.setOrganizationName("Pyxis")
app.setOrganizationDomain("Pyxis")
window = MainWindow()
window.show()
app.exec_()
You have to use the featurePermissionRequested signal that will be issued every time the browser requires permissions to use some resource, then open a dialog and if the user accepts or not then use setFeaturePermission() to accept or deny the feature:
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets
class WebEnginePage(QtWebEngineWidgets.QWebEnginePage):
def __init__(self, parent=None):
super(WebEnginePage, self).__init__(parent)
self.featurePermissionRequested.connect(self.handleFeaturePermissionRequested)
#QtCore.pyqtSlot(QtCore.QUrl, QtWebEngineWidgets.QWebEnginePage.Feature)
def handleFeaturePermissionRequested(self, securityOrigin, feature):
title = "Permission Request"
questionForFeature = {
QtWebEngineWidgets.QWebEnginePage.Geolocation : "Allow {feature} to access your location information?",
QtWebEngineWidgets.QWebEnginePage.MediaAudioCapture : "Allow {feature} to access your microphone?",
QtWebEngineWidgets.QWebEnginePage.MediaVideoCapture : "Allow {feature} to access your webcam?",
QtWebEngineWidgets.QWebEnginePage.MediaAudioVideoCapture : "Allow {feature} to lock your mouse cursor?",
QtWebEngineWidgets.QWebEnginePage.DesktopVideoCapture : "Allow {feature} to capture video of your desktop?",
QtWebEngineWidgets.QWebEnginePage.DesktopAudioVideoCapture: "Allow {feature} to capture audio and video of your desktop?"
}
question = questionForFeature.get(feature)
if question:
question = question.format(feature=securityOrigin.host())
if QtWidgets.QMessageBox.question(self.view().window(), title, question) == QtWidgets.QMessageBox.Yes:
self.setFeaturePermission(securityOrigin, feature, QtWebEngineWidgets.QWebEnginePage.PermissionGrantedByUser)
else:
self.setFeaturePermission(securityOrigin, feature, QtWebEngineWidgets.QWebEnginePage.PermissionDeniedByUser)
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.browser = QtWebEngineWidgets.QWebEngineView()
page = WebEnginePage(self.browser)
self.browser.setPage(page)
self.browser.load(QtCore.QUrl("https://developers.google.com/maps/documentation/javascript/examples/map-geolocation"))
self.setCentralWidget(self.browser)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.showMaximized()
sys.exit(app.exec())

Pyqt GUI suddenly not responding after clicked button 2 twice using QThread

i try create QThread class for my process, when i clicked Generate button it's don't show anything in my QTextEdit, when i click the button again my GUI suddenly not responding.
My Code
Updated Code
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import ipaddress
class Stream(QObject):
newText = pyqtSignal(str)
def write(self, text):
self.newText.emit(str(text))
def flush(self):
pass
class MyClass(object):
def __init__(self, device_type=None, ip=None, username=None, password=None, secret=None, command=None):
self.device_type = device_type
self.ip = ip
self.username = username
self.password = password
self.secret = secret
self.command = command
class sshConnection(QThread):
def __init__(self):
QThread.__init__(self)
def __del__(self):
self.wait()
def runSSH(self):
#doo process
print('Haii')
for x in range(100):
print(x)
class Widget(QWidget):
def __init__(self, parent=None):
QWidget.__init__(self, parent=parent)
self.device_list = [] # object array
self.setWindowTitle("Network Automation")
self.setFixedSize(350,500)
############################# Input IP
sys.stdout = Stream(newText=self.onUpdateText)
# Device Type
lb_device_list = QLabel(self)
lb_device_list.setText('Device Type')
self.cb_device_list = QComboBox(self)
self.cb_device_list.addItem('cisco_ios')
self.cb_device_list.addItem('cisco_s300')
# Ip Device
lb_ip = QLabel(self)
lb_ip.setText('IP Address')
self.le_ip = QLineEdit(self)
self.le_ip.setText('')
self.le_ip.setPlaceholderText('Input Device IP')
self.le_ip.setFixedWidth(150)
# username
lb_username = QLabel(self)
self.le_username = QLineEdit(self)
lb_username.setText('Username')
self.le_username.setText('')
self.le_username.setPlaceholderText('Input Username')
self.le_username.setFixedWidth(150)
# password
lb_password = QLabel(self)
self.le_password = QLineEdit(self)
lb_password.setText('Password')
self.le_password.setText('')
self.le_password.setPlaceholderText('Input Password')
self.le_password.setFixedWidth(150)
# Privilage Password
lb_enable = QLabel(self)
lb_enable.setText('Privilege Mode Password')
self.le_enable = QLineEdit(self)
self.le_enable.setText('')
self.le_enable.setPlaceholderText('Input Enable Password')
self.le_enable.setFixedWidth(150)
# button generate and add
btgenerate = QPushButton(self)
btgenerate.setText('Generate')
btgenerate.setFixedWidth(70)
btadd = QPushButton(self)
btadd.setText('Add')
# button delete
btdel = QPushButton(self)
btdel.setFixedWidth(70)
btdel.setText('Remove')
# line
line = QFrame(self)
line.setFrameShape(QFrame.VLine)
line.setFrameShadow(QFrame.Sunken)
line.setLineWidth(3)
#line 2
line2 = QFrame(self)
line2.setFrameShape(QFrame.HLine)
line2.setFrameShadow(QFrame.Sunken)
line2.setLineWidth(3)
########################### Layout Ip Device List
lb3 = QLabel(self)
lb3.setText('IP Device List')
self.ip_device_list = QListWidget(self)
self.ip_device_list.setFixedWidth(150)
# self.combobox_ip_list = QComboBox(self)
# self.combobox_ip_list.setFixedWidth(170)
############################## SubLayout and Layout
hblayout = QHBoxLayout()
hblayout.addWidget(btgenerate)
hblayout.addWidget(btadd)
############################### Processs
processlabel = QLabel("Process",self)
self.process = QTextEdit(self)
self.process.setLineWrapColumnOrWidth(400)
self.process.setLineWrapMode(QTextEdit.FixedPixelWidth)
self.process.setReadOnly(True)
sublayout = QVBoxLayout()
sublayout.addWidget(lb_device_list)
sublayout.addWidget(self.cb_device_list)
sublayout.addWidget(lb_ip)
sublayout.addWidget(self.le_ip)
sublayout.addWidget(lb_username)
sublayout.addWidget(self.le_username)
sublayout.addWidget(lb_password)
sublayout.addWidget(self.le_password)
sublayout.addWidget(lb_enable)
sublayout.addWidget(self.le_enable)
sublayout.addLayout(hblayout)
sublayout2 = QVBoxLayout()
sublayout2.addWidget(lb3)
sublayout2.addWidget(self.ip_device_list)
#sublayout2.addWidget(self.combobox_ip_list)
sublayout2.addWidget(btdel)
sublayout2.addStretch(1)
sublayout3 = QVBoxLayout()
sublayout3.addWidget(processlabel)
sublayout3.addWidget(self.process)
layout = QGridLayout(self)
layout.addLayout(sublayout, 0, 0)
layout.addWidget(line, 0, 1)
layout.addWidget(line2, 1, 0, 1, 3)
#layout.addWidget(processlabel,2,0)
layout.addLayout(sublayout3,2,0,2,3)
layout.addLayout(sublayout2, 0, 2)
btadd.clicked.connect(self.addDevice)
btdel.clicked.connect(self.remove)
btgenerate.clicked.connect(self.runThread)
def onUpdateText(self, text):
cursor = self.process.textCursor()
cursor.movePosition(QTextCursor.End)
cursor.insertText(text)
self.process.setTextCursor(cursor)
self.process.ensureCursorVisible()
# ----------- AddDevice Process
def addDevice(self):
try:
ip = self.le_ip.text()
ipaddress.ip_address(ip)
device_type = str(self.cb_device_list.currentText())
username = self.le_username.text()
password = self.le_password.text()
secret = self.le_enable.text()
command = 'show tech'
coomand2 = ''
self.device_list.append(MyClass(device_type, ip, username, password, secret, command))
# self.combobox_ip_list.addItem(ip)# Add Ip to ComboBox
self.ip_device_list.addItem(ip)
self.le_ip.clear()
self.le_username.clear()
self.le_password.clear()
self.le_enable.clear()
for list in self.device_list:
print(list.ip, list.device_type)
except ValueError:
print("insert you're ip correctly")
QMessageBox.question(self, 'Warning', "Insert You're IP Corecctly")
def remove(self):
index = self.ip_device_list.currentRow()
if index != -1:
self.ip_device_list.takeItem(index)
del self.device_list[index]
def runThread(self):
self.run_thread = sshConnection()
self.run_thread.finished.connect(app.exit)
self.run_thread.start()
app = QApplication(sys.argv)
app.setStyle('cleanlooks')
window = Widget()
window.show()
sys.exit(app.exec_())
QThread expects you to implement the run method, I think it is the same as runSSH but it is not, what you could do is call it in the run method, in the test that I show below I delete the line self.run_thread.finished.connect(app.exit)as it will close as soon as the print job does not take long.
class sshConnection(QThread):
def __init__(self):
QThread.__init__(self)
def __del__(self):
self.wait()
def run(self):
self.runSSH()
def runSSH(self):
#doo process
print('Haii')
for x in range(100):
print(x)

Creating a multi-window application in PySide

I am new to PySide, I want to create a multi-window application. For example, the first window will be login window, and if the login is correct then the login window should hide and the next window should appear.
How can I achieve this?
import sys
from PySide.QtGui import *
from PySide.QtCore import *
import chooseoption
class Form(QDialog):
def __init__(self, parent = None):
super(Form,self).__init__(parent)
self.usernamelabel = QLabel("Username : ")
self.passwordlabel = QLabel("Password : ")
self.username = QLineEdit()
self.password = QLineEdit()
self.okbutton = QPushButton("Login")
self.username.setPlaceholderText("Enter Username Here")
self.password.setPlaceholderText("Enter Password Here")
layout = QGridLayout()
layout.addWidget(self.usernamelabel,0,0)
layout.addWidget(self.passwordlabel,1,0)
layout.addWidget(self.username,0,1)
layout.addWidget(self.password,1,1)
layout.addWidget(self.okbutton)
self.setLayout(layout)
self.usernamelist = ['priyank','stupendo','ayaan']
self.passwordlist = ['priyank','stupendo','ayaan']
self.connect(self.okbutton, SIGNAL("clicked()"),self.loginfunction)
def loginfunction(self):
usernamestatus = False
usernameindex = -1
passwordstatus = False
passwordindex = -1
for currentusername in range(len(self.usernamelist)):
if self.passwordlist[currentusername] == self.username.text():
usernamestatus = True
usernameindex = self.usernamelist.index(self.passwordlist[currentusername])
for currentpassword in range(len(self.passwordlist)):
if self.usernamelist[currentpassword] ==self.password.text():
passwordstatus = True
passwordindex = self.passwordlist.index(self.usernamelist[currentpassword])
if usernamestatus == True and passwordstatus ==True and usernameindex == passwordindex:
w2 = chooseoption.Form1()
w2.show()
else:
self.msgBox = QMessageBox()
self.msgBox.setText("invalid!!!")
self.msgBox.exec_()
app = QApplication(sys.argv)
form = Form()
form.show()
sys.exit(app.exec_())
This is my chooseoption.py file:
import sys
from PySide.QtGui import *
from PySide.QtCore import *
class Form1(QDialog):
def __init__(self, parent = None):
super(Form1,self).__init__(parent)
self.addbutton = QPushButton("Add file in Important list")
self.removebutton = QPushButton("Remove file from Important list")
self.changeaddressbutton = QPushButton("Change Location of Important File")
layout = QHBoxLayout()
layout.addWidget(self.addbutton)
layout.addWidget(self.removebutton)
layout.addWidget(self.changeaddressbutton)
self.setLayout(layout)
The problem with this is that my second window just appears on the screen for a few milliseconds, and then disappears. How can I fix that?
code below creates three windows successively:
from PySide.QtCore import *
from PySide.QtGui import *
import sys
class W1(QWidget):
def __init__(self, parent=None):
super(W1, self).__init__(parent)
self.btn = QPushButton('Click1')
vb = QVBoxLayout()
vb.addWidget(self.btn)
self.setLayout(vb)
self.btn.clicked.connect(self.fireupWindows2)
def fireupWindows2(self):
w2 = W2()
if w2.exec_():
self.w3 = W3()
self.w3.show()
class W2(QDialog):
def __init__(self, parent=None):
super(W2, self).__init__(parent)
self.btn = QPushButton('Click2')
vb = QVBoxLayout()
vb.addWidget(self.btn)
self.setLayout(vb)
self.btn.clicked.connect(self.fireupWindows3)
def fireupWindows3(self):
self.accept()
class W3(QWidget):
def __init__(self, parent=None):
super(W3, self).__init__(parent)
self.resize(300, 300)
self.btn = QLabel('The Last Window')
vb = QVBoxLayout()
vb.addWidget(self.btn)
self.setLayout(vb)
if __name__ == "__main__":
app = QApplication(sys.argv)
w = W1()
w.show()
sys.exit(app.exec_())
Somehow I was able to solve above problem
test.py file:
import sys
from PySide.QtGui import *
from PySide.QtCore import *
import chooseoption
class Form(QDialog):
def __init__(self, parent = None):
super(Form,self).__init__(parent)
self.usernamelabel = QLabel("Username : ")
self.passwordlabel = QLabel("Password : ")
self.username = QLineEdit()
self.password = QLineEdit()
self.okbutton = QPushButton("Login")
self.username.setPlaceholderText("Enter Username Here")
self.password.setPlaceholderText("Enter Password Here")
layout = QGridLayout()
layout.addWidget(self.usernamelabel,0,0)
layout.addWidget(self.passwordlabel,1,0)
layout.addWidget(self.username,0,1)
layout.addWidget(self.password,1,1)
layout.addWidget(self.okbutton)
self.setLayout(layout)
self.usernamelist = ['priyank','stupendo','ayaan']
self.passwordlist = ['priyank','stupendo','ayaan']
self.connect(self.okbutton, SIGNAL("clicked()"),self.loginfunction)
def loginfunction(self):
usernamestatus = False
usernameindex = -1
passwordstatus = False
passwordindex = -1
for currentusername in range(len(self.usernamelist)):
if self.passwordlist[currentusername] == self.username.text():
usernamestatus = True
usernameindex = self.usernamelist.index(self.passwordlist[currentusername])
for currentpassword in range(len(self.passwordlist)):
if self.usernamelist[currentpassword] ==self.password.text():
passwordstatus = True
passwordindex = self.passwordlist.index(self.usernamelist[currentpassword])
if usernamestatus == True and passwordstatus ==True and usernameindex == passwordindex:
self.hide()
w2 = chooseoption.Form1(self)
w2.show()
else:
self.msgBox = QMessageBox()
self.msgBox.setText("Bloody Hacker!!!")
self.msgBox.exec_()
app = QApplication(sys.argv)
form = Form()
form.show()
sys.exit(app.exec_())
and this is a second window :
import sys
from PySide.QtGui import *
from PySide.QtCore import *
class Form1(QDialog):
def __init__(self, parent = None):
super(Form1,self).__init__(parent)
self.addbutton = QPushButton("Add file in Important list")
self.removebutton = QPushButton("Remove file from Important list")
self.changeaddressbutton = QPushButton("Change Location of Important File")
layout = QVBoxLayout()
layout.addWidget(self.addbutton)
layout.addWidget(self.removebutton)
layout.addWidget(self.changeaddressbutton)
self.setLayout(layout)
the important part is to hide the first window and create a object of second window with self as a parameter and then show second window
self.hide()
w2 = chooseoption.Form1(self)
w2.show()

Categories

Resources