Creating a multi-window application in PySide - python

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

Related

multiple subwindow with same widget QMdiSubwindow

i want to change object in all my subwindows
this is my code
import sys
from PyQt5.QtWidgets import *
from PyQt5 import QtWidgets
class MainWindow(QtWidgets.QMainWindow):
count = 0
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.mdi = QMdiArea()
self.setCentralWidget(self.mdi)
bar = self.menuBar()
file = bar.addMenu("Subwindow")
file.addAction("New")
file.addAction("Change Text")
file.triggered[QAction].connect(self.click)
self.setWindowTitle("Multiple window using MDI")
def click(self,action):
print("New sub window")
if action.text() == "New":
MainWindow.count = MainWindow.count + 1
sub = QMdiSubWindow()
sub.setWidget(QTextEdit())
sub.setWindowTitle("subwindow" + str(MainWindow.count))
self.subwindow = self.mdi.addSubWindow(sub)
self.subwindow.show()
self.label3 = QtWidgets.QLabel(sub)
self.label3.setGeometry(10, 80, 500, 10)
self.label3.setText('Default')
self.label3.show()
if action.text() == "Change Text":
for i in self.mdi.subWindowList():
label1 = QtWidgets.QLabel(i)
label1.setGeometry(10,50,500,10)
label1.setText(str(i))
label1.show()
self.label3.setText('TRUE')
print(i)
def main():
app = QApplication(sys.argv)
ex = MainWindow()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
but it's always the last creating order subwindow that changes
https://i.stack.imgur.com/DjZtf.png
how to change item in every subwindow?
how to change text table in subwindow i want with over 10 subwindow?
Right now your label3 is stored in MainWindow, so when you cycle through your subwindows you just change the latest label. You can store it in each subwindow like this:
import sys
from PyQt5.QtWidgets import *
from PyQt5 import QtWidgets
class MainWindow(QtWidgets.QMainWindow):
count = 0
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.mdi = QMdiArea()
self.setCentralWidget(self.mdi)
bar = self.menuBar()
file = bar.addMenu("Subwindow")
file.addAction("New")
file.addAction("Change Text")
file.triggered[QAction].connect(self.click)
self.setWindowTitle("Multiple window using MDI")
def click(self, action):
print("New sub window")
if action.text() == "New":
MainWindow.count = MainWindow.count + 1
sub = QMdiSubWindow()
sub.setWidget(QTextEdit())
sub.setWindowTitle("subwindow" + str(MainWindow.count))
self.subwindow = self.mdi.addSubWindow(sub)
self.subwindow.show()
# change current subwindow label text
button = QPushButton("Click to change", sub)
button.clicked.connect(lambda: sub.label3.setText('TRUE'))
sub.label3 = QtWidgets.QLabel(sub)
sub.label3.setGeometry(10, 80, 500, 10)
sub.label3.setText('Default')
sub_layout = self.subwindow.layout()
sub_layout.addWidget(sub.label3)
sub_layout.addWidget(button)
if action.text() == "Change Text":
for i in self.mdi.subWindowList():
label1 = QtWidgets.QLabel(i)
label1.setGeometry(10, 50, 500, 10)
label1.setText(str(i))
label1.show()
i.label3.setText('TRUE')
print(i)
def main():
app = QApplication(sys.argv)
ex = MainWindow()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()

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

How to update the progress bar using with pyqt4

Here it is sample program i want to update the my progress bar using with pyqt4.and i want to show th3 30% data saving and another 60% data processing.I am executing the my program it is aborting.Can any one please help me how to update the my progress bar.Thank you in advance.
Given below is my code:
import sys
import time
from pyface.qt import QtGui, QtCore
global X,Y
X= 5
Y= 4
import threading
class SaveWorker(QtCore.QObject):
progress_update = QtCore.Signal(int)
def save_file(self):
while True:
MyCustomWidget().updateProgressBar()
class Dialog(QtGui.QDialog):
def __init__(self, parent = None):
super(Dialog, self).__init__(parent)
self.setStyleSheet("QDialog {background-color:black; color:white }")
self.label1 = QtGui.QLabel(
text="Please Wait...",
font=QtGui.QFont("Times", 20,weight=QtGui.QFont.Bold)
)
self.progress = QtGui.QProgressBar()
self.box = QtGui.QVBoxLayout()
self.label2 = QtGui.QLabel()
vbox = QtGui.QVBoxLayout(self)
vbox.addWidget(self.label1)
vbox.addLayout(self.box)
self.show_gif()
def show_gif(self):
self.progress = QtGui.QProgressBar()
self.progress.setRange(0,100)
self.box.addWidget(self.progress)
self.show()
class MyCustomWidget(QtGui.QWidget):
def __init__(self, parent=None):
super(MyCustomWidget, self).__init__(parent)
self.worker = SaveWorker()
self.gif_dialog = Dialog()
self.worker.progress_update.connect(self.gif_dialog.show_gif)
thread = threading.Thread(target=self.worker.save_file)
thread.daemon = True
thread.start()
self.progressPer = 0
fileList = []
processes = []
_dataSavingPer = 30.0/(X*Y)
for i in range(X*Y):
name = 'file'+str(i+1) + ".txt"
fileList.append(name)
self.progressPer += _dataSavingPer
self.updateProgressBar(self.progressPer)
#updating the progress bar
_dataProcessPer = 60.0/(X*Y)
for file in fileList:
process = 'fileProcess'+str(i+1) + ".txt"
processes.append(process)
self.progressPer += _dataProcessPer
self.updateProgressBar(self.progressPer)
#Updating the progressPer
#how can i update these two values in to progressbar
def updateProgressBar(self,value):
self.gif_dialog.progress.setValue(value)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
window = MyCustomWidget()
sys.exit(app.exec_())
I do not understand what you tried when writing the following:
class SaveWorker(QtCore.QObject):
progress_update = QtCore.Signal(int)
def save_file(self):
while True:
MyCustomWidget().updateProgressBar()
updateProgressBar requires a value what value are you going through?, on the other hand when using MyCustomWidget() you are creating an object different from the one shown, and no MyCustomWidget object should be created in another thread.
What you have to do is move the heavy task to the save_file method since it will be executed in another thread:
import sys
import threading
from pyface.qt import QtGui, QtCore
X, Y = 5, 4
class SaveWorker(QtCore.QObject):
progressChanged = QtCore.Signal(int)
def save_file(self):
fileList = []
processes = []
_dataSavingPer = 30.0/(X*Y)
progress = 0
for i in range(X*Y):
name = 'file'+str(i+1) + ".txt"
fileList.append(name)
progress += _dataSavingPer
self.progressChanged.emit(progress)
_dataProcessPer = 60.0/(X*Y)
for file in fileList:
process = 'fileProcess'+str(i+1) + ".txt"
processes.append(process)
progress += _dataProcessPer
self.progressChanged.emit(progress)
class Dialog(QtGui.QDialog):
def __init__(self, parent = None):
super(Dialog, self).__init__(parent)
self.setStyleSheet("QDialog {background-color:black; color:white }")
self.label1 = QtGui.QLabel(
text="Please Wait...",
font=QtGui.QFont("Times", 20,weight=QtGui.QFont.Bold)
)
self.progress = QtGui.QProgressBar()
self.box = QtGui.QVBoxLayout()
self.label2 = QtGui.QLabel()
vbox = QtGui.QVBoxLayout(self)
vbox.addWidget(self.label1)
vbox.addLayout(self.box)
self.show_gif()
def show_gif(self):
self.progress = QtGui.QProgressBar()
self.progress.setRange(0,100)
self.box.addWidget(self.progress)
self.show()
class MyCustomWidget(QtGui.QWidget):
def __init__(self, parent=None):
super(MyCustomWidget, self).__init__(parent)
self.worker = SaveWorker()
self.gif_dialog = Dialog()
self.worker.progressChanged.connect(self.gif_dialog.progress.setValue)
thread = threading.Thread(target=self.worker.save_file)
thread.daemon = True
thread.start()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
window = MyCustomWidget()
sys.exit(app.exec_())

Unable to resize QTableWidget

I m trying to resize a table widget inside a QVBoxlayout which I further add as a row to a QFormlayout in pyqt
I m currently adding a QVboxlayout which contains a table widget inside it as a row in a Qformlayout.
And the main aim is to strecth the Table widget till the end of the application window that it acquires the left over space on the window
Using the below code -
class PGSearchDetails():
def __init__(self,parent=None):
self.widget_pgsd = QWidget()
self.layout_pgsd = QFormLayout()
self.layout_pgsd.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy(2|1))
self.PG_Id = QLineEdit()
#rx = QRegExp("^\\D+[!,#,#,$,%,\^,&,*,(,),:,\",{,},?,<,>,|,+,-,~,]")
#rx = QRegExp(" (?!(#,#,$|%|\^|&|*|(|)|:|\"|{|}|?|<|>|\||+|-|~|!))[\\w]+")
str_rx = QRegExp("^[A-Za-z*]{20}(?!##$%^&*():\"\{\}?<>\|+-~!_-)")
adhr_rx = QRegExp("[A-Z0-9]{12}(?!##$%^&*():\"\{\}?<>\|+-~!_)")
val = QRegExpValidator(str_rx)
val3 = QRegExpValidator(adhr_rx)
self.PG_Id.setValidator(val3)
self.LastName = QLineEdit()
self.LastName.setValidator(val)
self.MobNum = QLineEdit()
qint_val = QIntValidator()
qint_val.setTop(10)
self.MobNum.setValidator(qint_val)
self.layout_pgsd.addRow("First Name",self.PG_Id)
self.layout_pgsd.addRow("Last Name",self.LastName)
self.layout_pgsd.addRow("Mobile Number",self.MobNum)
update_layout_pgsd = QHBoxLayout()
layout_test,table = dbv.Search_View(self.getT)
#layout_test.setGeometry(QRect(200,200,50,50))
#table.setMaximumHeight(800)
#table.setGeometry(200,200,200,200)
#table.setGeometry(1,1,1000,600)
table.resize(1000,600)
update_btn_pgsd = QPushButton('Update')
reset_btn_pgsd = QPushButton('Reset')
update_layout_pgsd.addWidget(update_btn_pgsd)
update_layout_pgsd.addWidget(reset_btn_pgsd)
self.layout_pgsd.addRow(update_layout_pgsd)
##Adding the Table Widget to FormLayot
self.layout_pgsd.addRow(layout_test)
update_btn_pgsd.clicked.connect(partial(self.database,table,self.MobNum,
self.LastName))
#self.widget.setLayout(self.layout_pgsd)
def returnLayout(self):
return self.layout_pgsd
def returnWidget(self):
return self.widget_pgsd
def getT(self,linedit):
print("LE--->",linedit.text())
QtableWidget setup ---
def Search_View(self):
print("Inside Search_view")
central_widget = QWidget() # Create a central widget
db_layout = QVBoxLayout()
#col_count = len(self.pg_details.__dict__.keys())
col_count = 3
table = QTableWidget() # Create a table
#central_widget.setGeometry(200,200,150,150)
#table.maximumSize()
#db_layout.setMaximumSize(200)
db_layout.setGeometry(QRect(0,0,100,30))
db_layout.addWidget(table)
##Tried resizing the Table widget but nothing seems to works
table.resize(1000,600)
table.setGeometry(0,2,1000,600)
#central_widget.resize(central_widget.sizeHint())
#central_widget.setColumnWidth(1000,600)
#db_layout.addItem(update_layout)
central_widget.setLayout(db_layout)
print("Geometry H--->",table.geometry().height())
print("Geometry W--->",table.geometry().width())
print("Geometry X--->",table.geometry().x())
print("Geometry Y--->",table.geometry().y())
return central_widget,table
After the resize function, The table geometry changes to 1000,600 but on the screen it is not reflected. On the app screen it remains the same size everytime
Also find the entire code which contains the Tablayouts as well and Stacked widget for individual radio buttons
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.init_ui()
def init_ui(self):
self.tab_widget = MainTabWindow()
self.setCentralWidget(self.tab_widget)
self.show()
class MainTabWindow(QTabWidget):
def __init__(self,parent=None):
super(MainTabWindow, self).__init__(parent)
self.init_ui()
def init_ui(self):
self.setWindowTitle('PyQt5 Tab Example')
self.tab1 = QWidget()
self.addTab(self.tab1,"Search")
self.PGSearchTab()
def PGSearchTab(self):
print("Search Tab First Tab")
self.central_layout = QVBoxLayout()
self.stack1 = QWidget()
self.stack2 = QWidget()
self.stack3 = QWidget()
self.stack_widget = QStackedWidget()
button_layout = QHBoxLayout()
radio_button_1 = QRadioButton("Search")
radio_button_2 = QRadioButton("Add")
radio_button_3 = QRadioButton("Update")
button_layout.addWidget(radio_button_1)
button_layout.addWidget(radio_button_2)
button_layout.addWidget(radio_button_3)
self.central_layout.addItem(button_layout)
self.stack_widget.addWidget(self.stack1)
self.stack_widget.addWidget(self.stack2)
self.stack_widget.addWidget(self.stack3)
self.central_layout.addWidget(self.stack_widget)
radio_button_1.toggled.connect(lambda :self.SelectButtonCheck(radio_button_1))
self.setTabText(0,"Search")
update_layout = QHBoxLayout()
update_layout.setAlignment(QtCore.Qt.AlignBottom)
update_btn = QPushButton('Update')
reset_btn = QPushButton('Reset')
update_layout.addWidget(update_btn)
update_layout.addWidget(reset_btn)
self.tab1.setLayout(self.central_layout)
def SelectButtonCheck(self,b):
if b.text() == "Search":
if b.isChecked():
print(b.text()+ "is selected")
self.obj_pgsd = pgsd.PGSearchDetails()
layout = self.obj_pgsd.returnLayout()
if self.stack1.layout() is None:
self.stack1.setLayout(layout)
self.stack_widget.setCurrentIndex(0)
def main():
application = QApplication(sys.argv)
main_window = MainTabWindow()
main_window.show()
sys.exit(application.exec_())
if __name__ == '__main__':
main()
I do not seem to understand what is I m missing here
Any pointers would be appreciated.
Also find the working code to execute the above layout setup.
#!/usr/local/bin/python3
import sys
from PyQt5.QtWidgets import (QApplication, QWidget,QMainWindow,QLineEdit,QAction,
QLabel,QPushButton,QVBoxLayout,
QTabWidget,QFormLayout,QHBoxLayout,
QRadioButton,QCheckBox,QTextEdit,
QListView,QDialogButtonBox,QSizePolicy,QCalendarWidget)
from PyQt5 import QtCore
import PyQt5.Qt
from PyQt5.Qt import *
from PyQt5.QtCore import pyqtSlot
from PyQt5 import QtSql
from functools import partial
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.init_ui()
def init_ui(self):
self.tab_widget = MainTabWindow()
self.setCentralWidget(self.tab_widget)
self.show()
class MainTabWindow(QTabWidget):
def __init__(self,parent=None):
super(MainTabWindow, self).__init__(parent)
self.init_ui()
def init_ui(self):
self.setWindowTitle('PyQt5 Tab Example')
self.tab1 = QWidget()
self.addTab(self.tab1,"Search")
self.PGSearchTab()
def PGSearchTab(self):
print("Search Tab First Tab")
self.central_layout = QVBoxLayout()
self.stack1 = QWidget()
self.stack2 = QWidget()
self.stack3 = QWidget()
self.stack_widget = QStackedWidget()
button_layout = QHBoxLayout()
radio_button_1 = QRadioButton("Search")
radio_button_2 = QRadioButton("Add")
radio_button_3 = QRadioButton("Update")
button_layout.addWidget(radio_button_1)
button_layout.addWidget(radio_button_2)
button_layout.addWidget(radio_button_3)
self.central_layout.addItem(button_layout)
self.stack_widget.addWidget(self.stack1)
self.stack_widget.addWidget(self.stack2)
self.stack_widget.addWidget(self.stack3)
self.central_layout.addWidget(self.stack_widget)
radio_button_1.toggled.connect(lambda :self.SelectButtonCheck(radio_button_1))
self.setTabText(0,"Search")
update_layout = QHBoxLayout()
update_layout.setAlignment(QtCore.Qt.AlignBottom)
update_btn = QPushButton('Update')
reset_btn = QPushButton('Reset')
update_layout.addWidget(update_btn)
update_layout.addWidget(reset_btn)
self.tab1.setLayout(self.central_layout)
def SelectButtonCheck(self,b):
if b.text() == "Search":
if b.isChecked():
print(b.text()+ "is selected")
self.obj_pgsd = PGSearchDetails()
layout = self.obj_pgsd.returnLayout()
if self.stack1.layout() is None:
self.stack1.setLayout(layout)
self.stack_widget.setCurrentIndex(0)
class PGSearchDetails():
def __init__(self,parent=None):
self.widget_pgsd = QWidget()
self.layout_pgsd = QFormLayout()
self.layout_pgsd.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy(2|1))
self.PG_Id = QLineEdit()
#rx = QRegExp("^\\D+[!,#,#,$,%,\^,&,*,(,),:,\",{,},?,<,>,|,+,-,~,]")
#rx = QRegExp(" (?!(#,#,$|%|\^|&|*|(|)|:|\"|{|}|?|<|>|\||+|-|~|!))[\\w]+")
str_rx = QRegExp("^[A-Za-z*]{20}(?!##$%^&*():\"\{\}?<>\|+-~!_-)")
adhr_rx = QRegExp("[A-Z0-9]{12}(?!##$%^&*():\"\{\}?<>\|+-~!_)")
val = QRegExpValidator(str_rx)
val3 = QRegExpValidator(adhr_rx)
self.PG_Id.setValidator(val3)
self.LastName = QLineEdit()
self.LastName.setValidator(val)
self.MobNum = QLineEdit()
qint_val = QIntValidator()
qint_val.setTop(10)
self.MobNum.setValidator(qint_val)
self.layout_pgsd.addRow("First Name",self.PG_Id)
self.layout_pgsd.addRow("Last Name",self.LastName)
self.layout_pgsd.addRow("Mobile Number",self.MobNum)
update_layout_pgsd = QHBoxLayout()
layout_test,table = self.Search_View(self.getT)
#layout_test.setGeometry(QRect(200,200,50,50))
#table.setMaximumHeight(800)
#table.setGeometry(200,200,200,200)
#table.setGeometry(1,1,1000,600)
table.resize(1000,600)
update_btn_pgsd = QPushButton('Update')
reset_btn_pgsd = QPushButton('Reset')
update_layout_pgsd.addWidget(update_btn_pgsd)
update_layout_pgsd.addWidget(reset_btn_pgsd)
self.layout_pgsd.addRow(update_layout_pgsd)
##Adding the Table Widget to FormLayot
self.layout_pgsd.addRow(layout_test)
update_btn_pgsd.clicked.connect(partial(self.database,table,self.MobNum,
self.LastName))
#self.widget.setLayout(self.layout_pgsd)
def returnLayout(self):
return self.layout_pgsd
def returnWidget(self):
return self.widget_pgsd
def getT(self,linedit):
print("LE--->",linedit.text())
def Search_View(self,text):
print("Inside Search_view")
central_widget = QWidget() # Create a central widget
db_layout = QVBoxLayout()
#col_count = len(self.pg_details.__dict__.keys())
col_count = 3
table = QTableWidget() # Create a table
#central_widget.setGeometry(200,200,150,150)
#table.maximumSize()
#db_layout.setMaximumSize(200)
db_layout.setGeometry(QRect(0,0,100,30))
db_layout.addWidget(table)
##Tried resizing the Table widget but nothing seems to works
table.resize(1000,600)
table.setGeometry(0,2,1000,600)
#central_widget.resize(central_widget.sizeHint())
#central_widget.setColumnWidth(1000,600)
#db_layout.addItem(update_layout)
central_widget.setLayout(db_layout)
print("Geometry H--->",table.geometry().height())
print("Geometry W--->",table.geometry().width())
print("Geometry X--->",table.geometry().x())
print("Geometry Y--->",table.geometry().y())
return central_widget,table
def SqlExec(self,text):
db = QtSql.QSqlDatabase.addDatabase('QMYSQL')
db.setHostName('localhost')
db.setDatabaseName('Test')
db.setUserName('root')
db.open()
query = QtSql.QSqlQuery()
select = "select * from Test.PG_Details where PG_Id=?"# where PG_Id = 1"
query.prepare(select)
indexes = range(3)
print("TEXT----->",text)
query.addBindValue(text)
#query.exec_(select)
query.exec_()
print("Sizze----",query.size())
row_count = query.size()
db.record('PG_Details')
col_list = []
for i in range(db.record('PG_Details').count()):
print("FIELD----->",db.record('PG_Details').field(i).name())
col_list.append(db.record('PG_Details').field(i).name())
db.close()
return query,row_count,col_list
def database(self,table,text,text2):
text = text.text()
query_result,row_count,col_list = self.SqlExec(text)
i = 0
table.setColumnCount(3) #Set three columns
table.setRowCount(row_count)
table.setHorizontalHeaderLabels(col_list)
while query_result.next():
#print(query_result.value(i))
result_row = [query_result.value(index) for index in range(query_result.record().count())]
#print("RR--->",result_row)
for idx,val in enumerate(result_row):
#print("IDX----->",idx)
table.setItem(i, idx, QTableWidgetItem(val))
i = i + 1
def main():
application = QApplication(sys.argv)
main_window = MainTabWindow()
main_window.show()
sys.exit(application.exec_())
if __name__ == '__main__':
main()
The problem is that QFormLayout makes every time you add a widget using addRow () uses strech, the solution is to use a QVBoxLayout, and in that QVBoxLayout is to pass the QFormLayout and the layout_test.
class PGSearchDetails():
def __init__(self,parent=None):
self.widget_pgsd = QWidget()
self.layout = QVBoxLayout() # <---
self.layout_pgsd = QFormLayout()
self.layout.addLayout(self.layout_pgsd) # <---
self.layout_pgsd.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy(2|1))
...
self.layout_pgsd.addRow(update_layout_pgsd)
##Adding the Table Widget to FormLayot
# self.layout_pgsd.addRow(layout_test)
self.layout.addWidget(layout_test) # <---
update_btn_pgsd.clicked.connect(partial(self.database,table,self.MobNum,
self.LastName))
def returnLayout(self):
return self.layout # <---

How do I present 1 string per page?? (PyQt/Python)

I am trying to write a code which allows me to present one questions per page (without opening new windows). I wanted to know how i could alter the code below to allow me to do this??
import sys
from PyQt4 import QtCore, QtGui
class StartTest(QtGui.QMainWindow):
def __init__(self, parent=None):
super(StartTest, self).__init__(parent)
self.central_widget = QtGui.QStackedWidget()
self.setCentralWidget(self.central_widget)
QPage = Question(self)
self.central_widget.addWidget(QPage)
self.central_widget.setCurrentWidget(QPage)
class Question(QtGui.QWidget):
def __init__(self, label, parent=None):
super(Question, self).__init__(parent)
label = question1
question = QtGui.QLabel(label)
self.proceed = QtGui.QPushButton('Proceed')
self.Answer = QtGui.QLineEdit(self)
layout = QtGui.QFormLayout()
layout.addRow(question, self.Answer)
layout2 = QtGui.QVBoxLayout()
layout2.addLayout(layout)
layout2.addWidget(self.proceed)
self.setLayout(layout2)
self.proceed.clicked.connect(self.nextQ)
def nextQ(self):
Answer = self.Answer.text()
studentAns.append(Answer)
label = question2
studentAns = []
question1 = 'What is 5+5?'
question2 = 'What is 45+10?'
if __name__ == '__main__':
User = ''
app = QtGui.QApplication([])
window = StartTest()
window.showFullScreen()
app.exec_()
This should give you an idea of how to structure your program:
import sys
from PyQt4 import QtCore, QtGui
class StartTest(QtGui.QMainWindow):
def __init__(self, questions, parent=None):
super(StartTest, self).__init__(parent)
self.stack = QtGui.QStackedWidget(self)
self.setCentralWidget(self.stack)
for index, question in enumerate(questions):
page = Question(question, self)
page.submit.clicked[()].connect(
lambda index=index: self.handleSubmit(index))
self.stack.addWidget(page)
self.answers = []
def handleSubmit(self, index):
page = self.stack.widget(index)
answer = page.answer.text()
# validate submitted answer...
self.answers.append(answer)
if index < self.stack.count() - 1:
self.stack.setCurrentIndex(index + 1)
class Question(QtGui.QWidget):
def __init__(self, question, parent=None):
super(Question, self).__init__(parent)
self.question = QtGui.QLabel(question, self)
self.answer = QtGui.QLineEdit(self)
self.submit = QtGui.QPushButton('Submit', self)
form = QtGui.QFormLayout()
form.addRow(self.question, self.answer)
layout = QtGui.QVBoxLayout(self)
layout.addLayout(form)
layout.addWidget(self.submit)
if __name__ == '__main__':
User = ''
app = QtGui.QApplication([])
questions = [
'What is 5+5?',
'What is 45+10?',
'What is 28+47?',
'What is 22+13?',
]
window = StartTest(questions)
window.showFullScreen()
app.exec_()

Categories

Resources