location permission popup - python

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())

Related

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_())

pyqt closing a custom dialog in main window via mouse click

Q. is it possible, dialog closes itself and return color name just when user clicked or double clicked color item
Below is working example (hopefully to demonstrate problem). clicking on canvas area will pop up color dialog. currently user has to select color and then hit 'OK' button, where as intent is complete when user click on color. Just wanted to save user time, one bit.
import sys
from PyQt5 import QtCore, QtGui, QtWidgets, uic, QtMultimedia, QtMultimediaWidgets
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
colorsDict = { 'White': '0xFFFFFF','DarkGray': '0xA9A9A9','DarkSlateGray': '0x2F4F4F','LightSlateGray': '0x778899','DimGray': '0x696969','Gray': '0x808080','SlateGray': '0x708090','Black': '0x000000','DarkRed': '0x8B0000','Darkorange': '0xFF8C00','FireBrick': '0xB22222','Crimson': '0xDC143C','Salmon': '0xFA8072'}
def hexToQColor (h):
h = h.lstrip('#') # general usage safety
# h = h.lstrip('0x') # my use case
if h.find('0x') == 0:
h = h.split('0x')[1]
rgb = tuple(int(h[i:i+2], 16) for i in (0, 2 ,4))
return QColor(rgb[0],rgb[1],rgb[2])
class FfmpegColorDialog(QDialog):
"""
Custom FFMPEG Color Picker class
"""
resized = QtCore.pyqtSignal()
def __init__(self, parent=None):
super(FfmpegColorDialog, self).__init__(parent)
# self.ui = uic.loadUi('ui/ffmpeg_colors.ui', self)
self.setWindowTitle("FFMPEG Color Picker")
self.listWidget = QListWidget()
self.readPrefs()
self.listWidget.setFlow(QListView.LeftToRight)
self.listWidget.setResizeMode(QListView.Adjust)
self.listWidget.setGridSize(QSize(32, 32))
self.listWidget.setSpacing(5)
self.listWidget.setViewMode(QListView.IconMode)
self.listWidget.itemClicked.connect(self.itemClicked)
self.listWidget.itemDoubleClicked.connect(self.itemDoubleClicked)
layout = QVBoxLayout(self)
layout.addWidget(self.listWidget)
# OK and Cancel buttons
buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, self)
buttons.accepted.connect(self.accept)
buttons.rejected.connect(self.reject)
layout.addWidget(buttons)
def readPrefs(self):
"""
reading preferences from module for Data in UI
"""
for each in colorsDict.keys():
item = colorsDict[each]
listItem = QListWidgetItem()
listItem.setToolTip(each)
listItem.setSizeHint(QSize(30, 30))
color = hexToQColor(item)
listItem.setBackground(QBrush(color))
self.listWidget.addItem(listItem)
def itemClicked(self,item):
self.listWidget.setCurrentItem(item)
# self.accept()
def itemDoubleClicked(self,item):
c = item.background().color()
self.listWidget.setCurrentItem(item)
result = self.exec_()
return(c,result==QDialog.Accepted)
def getResults(self):
if self.exec_() == QDialog.Accepted:
item = self.listWidget.currentItem()
# print (item.toolTip())
return ( item.toolTip())
else:
return None
def getUserColor(self):
return (self.listWidget.currentItem().toolTip())
#staticmethod
def getFinalColor(parent=None):
dialog = FfmpegColorDialog(parent)
result = dialog.exec_()
color = dialog.getUserColor()
return(color,result==QDialog.Accepted)
class MainWindow(QMainWindow):
central_widget = None
layout_container = None
def __init__(self):
super(MainWindow, self).__init__()
self.central_widget = QWidget()
self.layout_container = QVBoxLayout()
self.central_widget.setLayout(self.layout_container)
self.setCentralWidget(self.central_widget)
self.layout_container.addWidget(GraphicsView())
class GraphicsView(QGraphicsView):
def __init__(self):
super(GraphicsView, self).__init__()
self.scene = QGraphicsScene()
self.setScene(self.scene)
self.text = None
self.createText()
def createText(self):
self.text = QGraphicsTextItem()
font = QFont()
font.setPixelSize(40)
self.text.setFont(font)
self.text.setPlainText("Sample Text To Test")
self.scene.addItem(self.text)
def mousePressEvent(self, event):
r,ok = FfmpegColorDialog.getFinalColor()
hc = colorsDict[r]
rgb = hexToQColor(hc)
self.text.setDefaultTextColor(rgb)
if __name__ == '__main__':
app = QApplication(sys.argv)
# dia = FfmpegColorDialog()
# dia.show()
mw = MainWindow()
mw.show()
sys.exit(app.exec_())
Just connect the clicked signal of the QListWidget to the accept slot of FfmpegColorDialog:
class FfmpegColorDialog(QDialog):
"""
Custom FFMPEG Color Picker class
"""
resized = QtCore.pyqtSignal()
def __init__(self, parent=None):
super(FfmpegColorDialog, self).__init__(parent)
# ...
self.listWidget = QListWidget()
self.listWidget.clicked.connect(self.accept) # <---
# ...

gui not responding during process?

I have sql query. My push button connects with sql - it takes long time. During it, my GUI is not responding - is it possible to make it responds?
QtCore.QCoreApplication.processEvents() doesnt work.
QApp.py
# -- coding: utf-8 --
from PyQt5 import QtGui, QtWidgets, QtCore
import qdarkstyle
import pyodbc
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow,self).__init__(parent)
self.main_frame()
self.center() #center frame
self.layout_init() #widgets layout
def main_frame(self):
### actions on meenubar
exitAct = QtWidgets.QAction('&Exit', self)
exitAct.setShortcut('Ctrl+Q')
exitAct.setStatusTip('Exit application')
exitAct.triggered.connect(self.close)
self.statusBar()
moreinfo = QtWidgets.QAction('&Help',self)
moreinfo.setStatusTip('More information')
moreinfo.triggered.connect(self.information)
self.statusBar()
### menubar
menubar = self.menuBar()
fileMenu = menubar.addMenu('&File')
fileMenu.addAction(exitAct)
fileMenu = menubar.addMenu('&Help')
fileMenu.addAction(moreinfo)
### basic geometry and color
self.setWindowTitle('Villain')
self.setWindowIcon(QtGui.QIcon('dc1.png'))
self.setStyleSheet((qdarkstyle.load_stylesheet_pyqt5()))
def layout_init(self):
self.grid = QtWidgets.QGridLayout()
central_widget = QtWidgets.QWidget()
self.setCentralWidget(central_widget)
### widgets
self.tablewidget = QtWidgets.QTableWidget()
self.tablewidget.setColumnCount(4)
self.tablewidget.setHorizontalHeaderLabels(["FileNameTransformed", "OrderItemCode", "Imported", "Row"])
self.tablewidget.horizontalHeader().setDefaultAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
self.tablewidget.horizontalHeader().setStretchLastSection(True)
self.tablewidget.resizeColumnsToContents()
self.tablewidget.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)
self.tablewidget.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
#self.tablewidget.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
self.textbox = QtWidgets.QLineEdit()
self.textbox.setPlaceholderText('IMEI')
self.textbox.setEnabled(True)
regexp = QtCore.QRegExp('^(0\d+|[1-9][0-9]+)$') #IMEI = only int
self.textbox.setValidator(QtGui.QRegExpValidator(regexp))
self.pb = QtWidgets.QPushButton(self.tr("Run process"))
self.pb.setDisabled(True)
self.textbox.textChanged.connect(self.disableButton)
self.pb.clicked.connect(self.on_clicked_pb)
self.clearbutton = QtWidgets.QPushButton(self.tr("Clear all"))
self.clearbutton.setDisabled(True)
self.clearbutton.clicked.connect(self.on_clicked_clear)
### make vidgets alive
self.centralWidget().setLayout(self.grid)
self.grid.addWidget(self.textbox)
self.grid.addWidget(self.tablewidget)
self.grid.addWidget(self.pb)
self.grid.addWidget(self.clearbutton)
### center main window
def center(self):
qr = self.frameGeometry()
cp = QtWidgets.QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
def information(self):
QtWidgets.QMessageBox.information(self,'Information','Version: 1.19.11.18\n'\
'This is the prototype of the application\n\n'\
'Please, contact karol.chojnowski#digitalcaregroup.com for comments and suggestions\n\n'\
'Digital Care - Data Processing Team')
def disableButton(self):
if len(self.textbox.text())> 0:
self.pb.setDisabled(False)
self.clearbutton.setDisabled(False)
else:
self.pb.setDisabled(True)
self.clearbutton.setDisabled(True)
### run process button
#QtCore.pyqtSlot()
def on_clicked_pb(self):
if len(self.textbox.text()) == 0:
pass
else:
self.sql_query()
### clear all
#QtCore.pyqtSlot()
def on_clicked_clear(self):
if len(self.textbox.text())> 0:
self.textbox.clear()
self.tablewidget.setRowCount(0)
self.tablewidget.setColumnWidth(3, 200)
def setCredentials(self, credentials):
self._credentials = credentials
def sql_query(self):
ser = "10.96.6.14"
base = "PROD_WAREX2"
username, pwd = self._credentials
QtCore.QCoreApplication.processEvents()
try:
self.connection = pyodbc.connect(driver='{SQL Server}', server=ser, database=base,
user=username, password=pwd)
cursor = self.connection.cursor()
self.res = cursor.execute(""" SELECT FI.FileNameTransformed,
FI.OrderItemCode,
FIR.Imported,
FR.Row
FROM [FileRows] AS FR
JOIN [FileImportRows] AS FIR ON FR.RowId = FIR.RowId
JOIN [FileImports] AS FI ON FIR.FileImportId = FI.Id
WHERE FR.Row LIKE ? """, ('%' + self.textbox.text() + '%'))
if not cursor.rowcount:
QtWidgets.QMessageBox.information(self, 'IMEI', "No items found")
cursor.close()
pass
else:
self.tablewidget.setRowCount(0)
for row, form in enumerate(self.res):
self.tablewidget.insertRow(row)
for column, item in enumerate(form):
newitem = QtWidgets.QTableWidgetItem(str(item))
self.tablewidget.setItem(row, column, newitem)
cursor.close()
self.table_performance()
self.tablewidget.sortItems(0, order=QtCore.Qt.DescendingOrder)
except:
QtWidgets.QMessageBox.warning(self, 'Error', "Something went wrong\n\n"\
"Contact karol.chojnowski#digitalcaregroup.com")
QtWidgets.QMessageBox.setStyleSheet((qdarkstyle.load_stylesheet_pyqt5()))
def table_performance(self):
self.tablewidget.resizeColumnsToContents()
self.tablewidget.setColumnWidth(3, 2500)
self.tablewidget.setHorizontalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel)
main .py:
Villain.py
# -- coding: utf-8 --
import sys
from PyQt5 import QtWidgets,QtGui
from QLogin import LoginDialog
from QApp import MainWindow
import os
def resource_path(relative_path):
if hasattr(sys, '_MEIPASS'):
return os.path.join(sys._MEIPASS, relative_path)
return os.path.join(os.path.abspath("."), relative_path)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
login = LoginDialog()
login.setWindowIcon(QtGui.QIcon(resource_path('dc1.png')))
if login.exec_() != QtWidgets.QDialog.Accepted:
sys.exit(-1)
window = MainWindow()
window.setWindowIcon(QtGui.QIcon(resource_path('dc1.png')))
window.setGeometry(500, 150, 800, 500)
window.setCredentials(login.credentials()) # <----
window.show()
sys.exit(app.exec_())
The use of processEvents() implies in most cases a bad design. If you have a heavy task, do not execute it in the main thread, execute it in another thread and send the necessary data to the main thread by means of signals or with QMetaObject::invokeMethod() (this last option will be used since it is not necessary so much connection).
On the other hand you should only add the stylesheet once, if there are new widgets they will take as a basis the stylesheet.
# -- coding: utf-8 --
import threading
from PyQt5 import QtGui, QtWidgets, QtCore
import qdarkstyle
import pyodbc
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow,self).__init__(parent)
self.main_frame()
self.center() #center frame
self.layout_init() #widgets layout
def main_frame(self):
### actions on meenubar
exitAct = QtWidgets.QAction('&Exit', self, shortcut='Ctrl+Q', statusTip='application')
exitAct.triggered.connect(self.close)
moreinfo = QtWidgets.QAction('&Help',self, statusTip='More information')
moreinfo.triggered.connect(self.information)
### menubar
menubar = self.menuBar()
fileMenu = menubar.addMenu('&File')
fileMenu.addAction(exitAct)
fileMenu = menubar.addMenu('&Help')
fileMenu.addAction(moreinfo)
### basic geometry and color
self.setWindowTitle('Villain')
self.setWindowIcon(QtGui.QIcon('dc1.png'))
self.setStyleSheet((qdarkstyle.load_stylesheet_pyqt5()))
def layout_init(self):
central_widget = QtWidgets.QWidget()
self.setCentralWidget(central_widget)
### widgets
self.tablewidget = QtWidgets.QTableWidget()
self.tablewidget.setColumnCount(4)
self.tablewidget.setHorizontalHeaderLabels(["FileNameTransformed", "OrderItemCode", "Imported", "Row"])
self.tablewidget.horizontalHeader().setDefaultAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
self.tablewidget.horizontalHeader().setStretchLastSection(True)
self.tablewidget.resizeColumnsToContents()
self.tablewidget.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)
self.tablewidget.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
#self.tablewidget.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
self.textbox = QtWidgets.QLineEdit()
self.textbox.setPlaceholderText('IMEI')
self.textbox.setEnabled(True)
regexp = QtCore.QRegExp('^(0\d+|[1-9][0-9]+)$') #IMEI = only int
self.textbox.setValidator(QtGui.QRegExpValidator(regexp))
self.pb = QtWidgets.QPushButton(self.tr("Run process"))
self.pb.setDisabled(True)
self.textbox.textChanged.connect(self.disableButton)
self.pb.clicked.connect(self.on_clicked_pb)
self.clearbutton = QtWidgets.QPushButton(self.tr("Clear all"))
self.clearbutton.setDisabled(True)
self.clearbutton.clicked.connect(self.on_clicked_clear)
### make vidgets alive
grid = QtWidgets.QGridLayout(central_widget)
grid.addWidget(self.textbox)
grid.addWidget(self.tablewidget)
grid.addWidget(self.pb)
grid.addWidget(self.clearbutton)
self.table_performance()
### center main window
def center(self):
qr = self.frameGeometry()
cp = QtWidgets.QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
def information(self):
QtWidgets.QMessageBox.information(self,'Information','Version: 1.19.11.18\n'\
'This is the prototype of the application\n\n'\
'Please, contact karol.chojnowski#digitalcaregroup.com for comments and suggestions\n\n'\
'Digital Care - Data Processing Team')
#QtCore.pyqtSlot()
def disableButton(self):
val = bool(self.textbox.text())
self.pb.setDisabled(not val)
self.clearbutton.setDisabled(not val)
### run process button
#QtCore.pyqtSlot()
def on_clicked_pb(self):
if self.textbox.text():
threading.Thread(target=self.sql_query, daemon=True).start()
### clear all
#QtCore.pyqtSlot()
def on_clicked_clear(self):
if self.textbox.text():
self.textbox.clear()
self.tablewidget.setRowCount(0)
self.tablewidget.setColumnWidth(3, 200)
def setCredentials(self, credentials):
self._credentials = credentials
def table_performance(self):
self.tablewidget.resizeColumnsToContents()
self.tablewidget.setColumnWidth(3, 2500)
self.tablewidget.setHorizontalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel)
#QtCore.pyqtSlot(str, str)
def show_warning(self, title, msg):
QtWidgets.QMessageBox.information(self, title, msg)
#QtCore.pyqtSlot()
def clear_items(self):
self.tablewidget.setRowCount(0)
#QtCore.pyqtSlot(int, int, str)
def add_item(self, row, column, val):
if row >= self.tablewidget.rowCount():
self.tablewidget.insertRow(self.tablewidget.rowCount())
newitem = QtWidgets.QTableWidgetItem(val)
self.tablewidget.setItem(row, column, newitem)
#QtCore.pyqtSlot()
def sort_items(self):
self.tablewidget.sortItems(0, order=QtCore.Qt.DescendingOrder)
def sql_query(self):
ser = "10.96.6.14"
base = "PROD_WAREX2"
username, pwd = self._credentials
try:
connection = pyodbc.connect(driver='{SQL Server}', server=ser, database=base,
user=username, password=pwd)
cursor = connection.cursor()
res = cursor.execute(""" SELECT FI.FileNameTransformed,
FI.OrderItemCode,
FIR.Imported,
FR.Row
FROM [FileRows] AS FR
JOIN [FileImportRows] AS FIR ON FR.RowId = FIR.RowId
JOIN [FileImports] AS FI ON FIR.FileImportId = FI.Id
WHERE FR.Row LIKE ? """, ('%' + self.textbox.text() + '%'))
if not cursor.rowcount:
QtCore.QMetaObject.invokeMethod(self, "show_warning",
QtCore.Qt.QueuedConnection,
QtCore.Q_ARG(str, 'IMEI'), QtCore.Q_ARG(str, "No items found"))
else:
QtCore.QMetaObject.invokeMethod(self, "clear_items", QtCore.Qt.QueuedConnection)
QtCore.QThread.msleep(10)
for row, form in enumerate(res):
for column, item in enumerate(form):
QtCore.QMetaObject.invokeMethod(self, "add_item",
QtCore.Qt.QueuedConnection,
QtCore.Q_ARG(int, row), QtCore.Q_ARG(int, column), QtCore.Q_ARG(str, str(item)))
QtCore.QThread.msleep(10)
QtCore.QMetaObject.invokeMethod(self, "sort_items", QtCore.Qt.QueuedConnection)
cursor.close()
except:
QtCore.QMetaObject.invokeMethod(self, "show_warning",
QtCore.Qt.QueuedConnection,
QtCore.Q_ARG(str, 'Error'), QtCore.Q_ARG(str, "Something went wrong\n\n"\
"Contact karol.chojnowski#digitalcaregroup.com"))

PyQt4 : making certain text on QTextEdit uneditable

Is there any way I can make certain text on QTextEdit permanent. Applications like cmd.exe where the current user directory is displayed and the rest of the screen is up for input. I tried inserting a QLabel but unable to do so, here's my code, I am currently taking user input through a separate line edit.
UPDATE I had a look at Ipython QtConsole where the line number is displayed constantly, how can I do that, I am looking in the source but if anyone who already knows it, please do tell. Here is the QtConsole for ipython notebook, I am trying to replicate this.
import os
import sys
import PyQt4
import PyQt4.QtCore
from PyQt4.QtGui import *
def main():
app = QApplication(sys.argv)
w = MyWindow()
w.show()
sys.exit(app.exec_())
class MyWindow(QWidget):
def __init__(self, *args):
QWidget.__init__(self, *args)
# create objects
label = QLabel(self.tr("Enter command and press Return"))
self.le = QLineEdit()
self.te = QTextEdit()
self.lbl = QLabel(str(os.getcwd())+"> ")
# layout
layout = QVBoxLayout(self)
layout.addWidget(label)
layout.addWidget(self.le)
layout.addWidget(self.te)
self.setLayout(layout)
# styling
self.te.setReadOnly(True)
# create connection
self.mytext = str(self.le.text())
self.connect(self.le, PyQt4.QtCore.SIGNAL("returnPressed(void)"),
self.display)
def display(self):
mytext = str(self.le.text())
self.te.append(self.lbl +str(os.popen(mytext).read()))
self.le.setText("")
if __name__ == "__main__":
main()
A simple solution is to create a class that inherits from QTextEdit and overwrite and add the necessary attributes as shown below:
class TextEdit(QTextEdit):
def __init__(self, *args, **kwargs):
QTextEdit.__init__(self, *args, **kwargs)
self.staticText = os.getcwd()
self.counter = 1
self.setReadOnly(True)
def append(self, text):
n_text = "{text} [{number}] > ".format(text=self.staticText, number=self.counter)
self.counter += 1
QTextEdit.append(self, n_text+text)
Complete Code:
import os
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class TextEdit(QTextEdit):
def __init__(self, *args, **kwargs):
QTextEdit.__init__(self, *args, **kwargs)
self.staticText = os.getcwd()
self.counter = 1
self.setReadOnly(True)
def append(self, text):
n_text = "{text} [{number}] > ".format(text=self.staticText, number=self.counter)
self.counter += 1
QTextEdit.append(self, n_text+text)
class MyWindow(QWidget):
def __init__(self, *args, **kwargs):
QWidget.__init__(self, *args, **kwargs)
label = QLabel(self.tr("Enter command and press Return"), self)
self.le = QLineEdit(self)
self.te = TextEdit(self)
# layout
layout = QVBoxLayout(self)
layout.addWidget(label)
layout.addWidget(self.le)
layout.addWidget(self.te)
self.setLayout(layout)
self.connect(self.le, SIGNAL("returnPressed(void)"), self.display)
# self.le.returnPressed.connect(self.display)
def display(self):
command = str(self.le.text())
resp = str(os.popen(command).read())
self.te.append(resp)
self.le.clear()
def main():
app = QApplication(sys.argv)
w = MyWindow()
w.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
To emulate QtConsole we must overwrite some methods of QTextEdit, catch some events, and verify that it does not eliminate the prefix as I show below:
import os
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class TextEdit(QTextEdit):
def __init__(self, *args, **kwargs):
QTextEdit.__init__(self, *args, **kwargs)
self.staticText = os.getcwd()
self.counter = 1
self.prefix = ""
self.callPrefix()
self.setContextMenuPolicy(Qt.CustomContextMenu)
self.customContextMenuRequested.connect(self.onCustomContextMenuRequest)
def onCustomContextMenuRequest(self, point):
menu = self.createStandardContextMenu()
for action in menu.actions():
if "Delete" in action.text():
action.triggered.disconnect()
menu.removeAction(action)
elif "Cu&t" in action.text():
action.triggered.disconnect()
menu.removeAction(action)
elif "Paste" in action.text():
action.triggered.disconnect()
act = menu.exec_(point)
if act:
if "Paste" in act.text():
self.customPaste()
def customPaste(self):
self.moveCursor(QTextCursor.End)
self.insertPlainText(QApplication.clipboard().text())
self.moveCursor(QTextCursor.End)
def clearCurrentLine(self):
cs = self.textCursor()
cs.movePosition(QTextCursor.StartOfLine)
cs.movePosition(QTextCursor.EndOfLine)
cs.select(QTextCursor.LineUnderCursor)
text = cs.removeSelectedText()
def isPrefix(self, text):
return self.prefix == text
def getCurrentLine(self):
cs = self.textCursor()
cs.movePosition(QTextCursor.StartOfLine)
cs.movePosition(QTextCursor.EndOfLine)
cs.select(QTextCursor.LineUnderCursor)
text = cs.selectedText()
return text
def keyPressEvent(self, event):
if event.key() == Qt.Key_Return:
command = self.getCurrentLine()[len(self.prefix):]
self.execute(command)
self.callPrefix()
return
elif event.key() == Qt.Key_Backspace:
if self.prefix == self.getCurrentLine():
return
elif event.matches(QKeySequence.Delete):
return
if event.matches(QKeySequence.Paste):
self.customPaste()
return
elif self.textCursor().hasSelection():
t = self.toPlainText()
self.textCursor().clearSelection()
QTextEdit.keyPressEvent(self, event)
self.setPlainText(t)
self.moveCursor(QTextCursor.End)
return
QTextEdit.keyPressEvent(self, event)
def callPrefix(self):
self.prefix = "{text} [{number}] >".format(text=self.staticText, number=self.counter)
self.counter += 1
self.append(self.prefix)
def execute(self, command):
resp = os.popen(command).read()
self.append(resp)
class MyWindow(QWidget):
def __init__(self, *args, **kwargs):
QWidget.__init__(self, *args, **kwargs)
label = QLabel(self.tr("Enter command and press Return"), self)
self.te = TextEdit(self)
# layout
layout = QVBoxLayout(self)
layout.addWidget(label)
layout.addWidget(self.te)
self.setLayout(layout)
def main():
app = QApplication(sys.argv)
w = MyWindow()
w.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()

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