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()
Related
I have a scenario where one window is running in python Pyqt5. I want that when certain event happens another window also opens up.
I have written a code which I suppose should run fine but when event occurs to open other GUI, I gets an error.
My code:
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
app = QApplication(sys.argv)
win = QWidget()
l1 = QLabel("URL:")
url = QLineEdit()
l3 = QLabel("Wait (sec):")
wait = QLineEdit()
l2 = QLabel("Iteration:")
l2.move(20,100)
global add1
count = QLineEdit()
fbox = QFormLayout()
fbox.addRow(l1, url)
fbox.addRow(l3, wait)
vbox = QVBoxLayout()
vbox.addWidget(count)
fbox.addRow(l2, vbox)
startButton=QPushButton("Start")
fbox.addRow(startButton)
startButton.clicked.connect(self.requests)
win.setLayout(fbox)
win.setWindowTitle("--")
win.resize(300,200)
win.show()
sys.exit(app.exec_())
def requests(self):
for x in range(0,int(count.text())):
//certain event happens here, which will cause other window to get open
self.dialog = PopUp(self)
self.dialog.show()
def stop(self):
sys.exit()
class PopUp(QMainWindow):
def __init__(self, parent=None):
super(PopUp, self).__init__(parent)
app = QApplication(sys.argv)
win = QWidget()
l1 = QLabel("URL:")
nextUrl = QLineEdit()
fbox = QFormLayout()
fbox.addRow(l1, url)
startButton = QPushButton("Go")
fbox.addRow(startButton)
startButton.clicked.connect(self.requests)
win.setLayout(fbox)
win.setWindowTitle("--")
win.resize(300, 200)
win.show()
sys.exit(app.exec_())
if __name__ == '__main__':
app = QApplication(sys.argv)
main = MainWindow()
main.show()
sys.exit(app.exec_())
I see that code is right but I am getting an unknown error:
QCoreApplication::exec: The event loop is already running
I have searched on google and here in stack overflow but didn't get anything worthy. Anyone knows that why this error comes and why is it coming in my code??
Each PyQt5 application must create one application object app = QApplication(sys.argv). Remove from the class MainWindow and the class PopUp - app = QApplication (sys.argv) .
sys.exit(app.exec_()) - the mainloop of the application, he must also be alone. Remove from the class MainWindow and the class PopUp - sys.exit(app.exec_())
I improved the readability of your example a bit.
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class PopUp(QMainWindow):
def __init__(self, x, url, parent=None):
super(PopUp, self).__init__(parent)
self.url = url.text()
self.x = x + 1
self.setWindowTitle("-- PopUp {} --".format(self.x))
self.setGeometry(self.x*100, self.x*100, 300, 200)
win = QWidget()
self.setCentralWidget(win)
nextUrl = QLineEdit(self.url)
self.startButton = QPushButton("Go {}".format(self.x))
fbox = QFormLayout(win)
fbox.addRow(QLabel("URL:"), nextUrl)
fbox.addRow(self.startButton)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.dialogs = []
self.flag = False
win = QWidget()
self.setCentralWidget(win)
self.url = QLineEdit() # + self
wait = QLineEdit()
self.count = QLineEdit() # + self
startButton = QPushButton("Start")
startButton.clicked.connect(self.requests)
fbox = QFormLayout(win)
fbox.addRow(QLabel("URL:"), self.url)
fbox.addRow(QLabel("Wait (sec):"), wait)
fbox.addRow(QLabel("Iteration:"), self.count)
fbox.addRow(startButton)
def requests(self):
if self.dialogs and self.flag:
_ = [ i.hide() for i in self.dialogs]
self.dialogs = []
for x in range(0, int(self.count.text())):
# certain event happens here, which will cause other window to get open
dialog = PopUp(x, self.url, self)
dialog.startButton.clicked.connect(self.requests2)
dialog.show()
self.dialogs.append(dialog)
self.flag = True
def stop(self): # ?
sys.exit()
def requests2(self):
print("def requests2(self): clicked Button {}".format(self.sender().text()))
if __name__ == '__main__':
app = QApplication(sys.argv)
main = MainWindow()
main.setWindowTitle("-- Title --")
main.resize(300,200)
main.show()
sys.exit(app.exec_())
See my code and tell me how do I set progress bar to the -dollar()- function and progress bar start with doing the function and finished with it. see my code at the continue:
from PyQt5.QtWidgets import (QWidget,QApplication,QTextEdit,
QInputDialog,QPushButton,QVBoxLayout,QProgressBar)
import sys
class Tbx(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.vbox = QVBoxLayout()
self.btn = QPushButton('ClickMe',self)
self.btn.clicked.connect(self.dollar)
self.te = QTextEdit(self)
self.prgb = QProgressBar(self)#How to set this to doing something?
self.vbox.addWidget(self.te)
self.vbox.addWidget(self.btn)
self.vbox.addWidget(self.prgb)
self.setLayout(self.vbox)
self.setGeometry(300,300,400,250)
self.setWindowTitle('Application')
self.show()
def dollar(self):#Like doing this set progress bar to this
text_1_int , ok = QInputDialog.getInt(self,'HowMany?','Enter How Many dollar do you want ?')
if not ok:
return
current_lines = self.te.toPlainText().split('\n')
new_lines = list()
for dollar_counter in range(1,text_1_int+1):
word = '$'*dollar_counter
new_lines += [word + text for text in current_lines]
self.te.setPlainText('\n'.join(new_lines))
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Tbx()
sys.exit(app.exec_())
You can set the maximum value of the progress control to the value entered in your input window and then simply use setValue to increase the progress bar, however, this will block the UI for very large calculations, so you might want to also move your method to a new thread and report progress to the UI using a signal, here is the full example:
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.QtWidgets import (QWidget, QApplication, QTextEdit, QInputDialog, QPushButton, QVBoxLayout, QProgressBar)
import sys
class DollarCalculation(QThread):
reportProgress = pyqtSignal(int, list)
calculationFinished = pyqtSignal()
def __init__(self, numDollars, currentLines):
super().__init__()
self.numDollars = numDollars
self.currentLines = currentLines
def run(self) -> None:
for dollar_counter in range(1, self.numDollars + 1):
word = '$' * dollar_counter
self.reportProgress.emit(dollar_counter + 1, [word + text for text in self.currentLines])
self.calculationFinished.emit()
class Tbx(QWidget):
def __init__(self):
super().__init__()
self.initUI()
self.dollarCalculation = None
def initUI(self):
self.vbox = QVBoxLayout()
self.btn = QPushButton('ClickMe', self)
self.btn.clicked.connect(self.dollar)
self.te = QTextEdit(self)
self.prgb = QProgressBar(self)
self.vbox.addWidget(self.te)
self.vbox.addWidget(self.btn)
self.vbox.addWidget(self.prgb)
self.setLayout(self.vbox)
self.setGeometry(300, 300, 400, 250)
self.setWindowTitle('Application')
def dollar(self):
text_1_int, ok = QInputDialog.getInt(self, 'HowMany?', 'Enter How Many dollar do you want ?')
if not ok:
return
self.btn.setEnabled(False)
self.prgb.setMaximum(text_1_int + 1)
self.dollarCalculation = DollarCalculation(text_1_int, self.te.toPlainText().split('\n'))
self.dollarCalculation.reportProgress.connect(self.progress)
self.dollarCalculation.calculationFinished.connect(self.calculationFinished)
self.dollarCalculation.start()
def progress(self, value, newLines):
self.te.append('\n'.join(newLines))
self.prgb.setValue(value)
def calculationFinished(self):
self.btn.setEnabled(True)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Tbx()
ex.show()
sys.exit(app.exec_())
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 can I force the splitter to be positioned in the center of the window at the start? As you can see in the code below it favors the right side because of the button being small. however I would like to have the splitter always appear in the middle of the window as shown in image two.
Current
Goal
import sys
from PySide import QtGui, QtCore
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
# formatting
self.resize(550, 400)
self.setWindowTitle("Cameras")
# widgets
self.ListA = QtGui.QTreeWidget()
self.ListB = QtGui.QTreeWidget()
self.Button = QtGui.QPushButton()
# layout Splitter
self.mainLayout = QtGui.QHBoxLayout(self)
self.mainLayout.setContentsMargins(5,5,5,5)
self.leftPanel = QtGui.QFrame(self)
# self.leftPanel.setFrameShape(QtGui.QFrame.StyledPanel)
self.leftPanelLayout = QtGui.QHBoxLayout(self.leftPanel)
self.leftPanelLayout.setContentsMargins(0,0,0,0)
self.leftPanelLayout.addWidget(self.ListA)
self.rightPanel = QtGui.QFrame(self)
# self.rightPanel.setFrameShape(QtGui.QFrame.StyledPanel)
self.rightPanelLayout = QtGui.QHBoxLayout(self.rightPanel)
self.rightPanelLayout.setContentsMargins(0,0,0,0)
self.rightPanelLayout.addWidget(self.Button)
self.splitter = QtGui.QSplitter(QtCore.Qt.Horizontal)
self.splitter.addWidget(self.leftPanel)
self.splitter.addWidget(self.rightPanel)
self.mainLayout.addWidget(self.splitter)
self.setGeometry(300, 300, 300, 200)
self.setWindowTitle('QtGui.QSplitter')
self.show()
def onChanged(self, text):
self.lbl.setText(text)
self.lbl.adjustSize()
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Bam! got it.
import sys
from PySide import QtGui, QtCore
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
# formatting
self.resize(1000, 1000)
self.setWindowTitle("Cameras")
# widgets
self.ListA = QtGui.QTreeWidget()
self.ListB = QtGui.QTreeWidget()
self.Button = QtGui.QPushButton()
# layout Splitter
# QHBoxLayout
self.mainLayout = QtGui.QGridLayout(self)
self.mainLayout.setContentsMargins(5,5,5,5)
self.leftPanel = QtGui.QFrame(self)
# self.leftPanel.setFrameShape(QtGui.QFrame.StyledPanel)
self.leftPanelLayout = QtGui.QHBoxLayout(self.leftPanel)
self.leftPanelLayout.setContentsMargins(0,0,0,0)
self.leftPanelLayout.addWidget(self.ListA)
self.rightPanel = QtGui.QFrame(self)
# self.rightPanel.setFrameShape(QtGui.QFrame.StyledPanel)
self.rightPanelLayout = QtGui.QHBoxLayout(self.rightPanel)
self.rightPanelLayout.setContentsMargins(0,0,0,0)
self.rightPanelLayout.addWidget(self.Button)
self.splitter = QtGui.QSplitter(QtCore.Qt.Horizontal)
self.splitter.addWidget(self.leftPanel)
self.splitter.addWidget(self.rightPanel)
self.splitter.setCollapsible(0,False)
self.splitter.setCollapsible(1,False)
self.mainLayout.addWidget(self.splitter,0,0)
self.setWindowTitle('QtGui.QSplitter')
self.show()
self.set_panel_sizes(self.splitter)
def onChanged(self, text):
self.lbl.setText(text)
self.lbl.adjustSize()
def set_panel_sizes(self, ctrl):
width = ctrl.frameSize().width() / 2.0
ctrl.setSizes( [width,width] )
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
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()