How can I change the Tab beeing shown by pressing an button ?
The function is beeing called by pressing a button in a message box.
I have tried setCurrentIndex() but the Tab beeing shown will not change.
I am using Python 3.6 and pyqt5.
Here is my Code:
import sys
from PyQt5 import QtWidgets, QtCore, QtPrintSupport, QtGui
from PyQt5.QtWidgets import *
class main_window(QTabWidget):
def __init__(self, parent=None):
super(QTabWidget, self).__init__(parent)
self.setGeometry(50, 50, 1100, 750)
self.setWindowTitle("Programm") #
self.centralWidget = QtWidgets.QWidget()
self.tabWidget = QtWidgets.QTabWidget(self.centralWidget)
self.tabWidget.setGeometry(QtCore.QRect(10, 10, 1200, 1000))
self.tabWidget.setLayoutDirection(QtCore.Qt.LeftToRight)
self.tabWidget.setTabPosition(QtWidgets.QTabWidget.West)
self.tab_v1 = QtWidgets.QWidget()
self.addTab(self.tab_v1, "Tab 1")
self.tab_v2 = QtWidgets.QWidget()
self.addTab(self.tab_v2, "Tab 2")
self.tab_v3 = QtWidgets.QWidget()
self.addTab(self.tab_v3, "Tab 3")
self.openFile = QPushButton("Choose Tab ", self.tab_v1)
self.openFile.setGeometry(QtCore.QRect(700, 25, 200, 30))
self.openFile.clicked.connect(self.on_click_do)
def on_click_do(self):
box1 = QMessageBox()
box1.setIcon(QMessageBox.Question)
box1.setWindowTitle('Information')
box1.setText(
"Do you want to go to the next Tab?")
box1.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
buttonY = box1.button(QMessageBox.Yes)
buttonY.setText('Yes') ##translation
buttonN = box1.button(QMessageBox.No)
buttonN.setText('No') ## translation
box1.exec_()
if box1.clickedButton() == buttonN:
pass
elif box1.clickedButton() == buttonY:
self.tabWidget.setCurrentIndex(1)
def main():
app = QApplication(sys.argv)
ex = main_window()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Try it:
import sys
from PyQt5 import QtWidgets, QtCore, QtPrintSupport, QtGui
from PyQt5.QtWidgets import *
class main_window(QTabWidget):
def __init__(self, parent=None):
super(QTabWidget, self).__init__(parent)
self.setGeometry(50, 50, 1100, 750)
self.setWindowTitle("Programm") #
self.centralWidget = QtWidgets.QWidget()
self.tabWidget = QtWidgets.QTabWidget(self.centralWidget)
self.tabWidget.setGeometry(QtCore.QRect(10, 10, 1200, 1000))
self.tabWidget.setLayoutDirection(QtCore.Qt.LeftToRight)
self.tabWidget.setTabPosition(QtWidgets.QTabWidget.West)
self.tab_v1 = QtWidgets.QWidget()
self.addTab(self.tab_v1, "Tab 1")
self.tab_v2 = QtWidgets.QWidget()
self.addTab(self.tab_v2, "Tab 2")
self.tab_v3 = QtWidgets.QWidget()
self.addTab(self.tab_v3, "Tab 3")
self.openFile = QPushButton("Choose Tab ", self.tab_v1)
self.openFile.setGeometry(QtCore.QRect(700, 25, 200, 30))
self.openFile.clicked.connect(self.on_click_do)
def on_click_do(self):
box1 = QMessageBox()
box1.setIcon(QMessageBox.Question)
box1.setWindowTitle('Information')
box1.setText(
"Do you want to go to the next Tab?")
box1.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
buttonY = box1.button(QMessageBox.Yes)
buttonY.setText('Yes') ##translation
buttonN = box1.button(QMessageBox.No)
buttonN.setText('No') ## translation
box1.exec_()
if box1.clickedButton() == buttonN:
pass
elif box1.clickedButton() == buttonY:
#self.tabWidget.setCurrentIndex(1) # ---
self.setCurrentIndex(1) # +++
def main():
app = QApplication(sys.argv)
ex = main_window()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Related
In the window click Edit -> Add Row. dlg1 Dialog is executed. By default there is a data to get an error because it tries to open dlg2 Dialog. If value in the fist row is changed dlg3 Dialog will be shown.
How to i get dlg2 Dialog to show up?
How do i close dlg1 Dialog after pressing a button in it?
What am i doing wrong?
main.py
#!/usr/bin/python3
import sys
import getopt
import json, csv
import os.path
import pip
#-------------------------------------------------
from datetime import datetime, date
from dateutil.relativedelta import relativedelta
#-------------------------------------------------
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from main_window_ui import Ui_MainWindow
#-------------------------------------------------
data = [{"edrpou": "44444", "name": "Org Name 1", "serviced": ""},{"edrpou": "5666667", "name": "Org Name 2", "serviced": ""}]
fileEReports = 'data.json'
inEdrpou = ""
##################################################
def check_spaces(whatT):
w = 0
while w == 0:
whatF = input(whatT)
if (' ' in whatF):
print("error, no space allowed!")
else:
w = 1
return whatF
##################################################
def add_data_to_file(filer):
isExist = os.path.exists(filer)
if isExist == False:
with open(filer, "w+") as write_file:
#json.dump(data, write_file, sort_keys=True, indent=4, separators=(',', ': '))
json.dump(data, write_file)
write_file.close()
##################################################
def get_orgs_from_file(filer):
with open(filer, "r") as read_file:
for jsonObj in read_file:
orgsDict = json.loads(jsonObj)
read_file.close()
return orgsDict
def write_orgs_to_file(filer, data):
with open(filer, "w+") as write_file:
json.dump(data, write_file)
write_file.close()
##################################################
class MainWindow(QMainWindow, Ui_MainWindow):
def __init__(self):
QMainWindow.__init__(self)
Ui_MainWindow.__init__(self)
super(MainWindow, self).__init__()
self.setupUi(self)
###################### vars ######################
self.action_add_row_orgs.triggered.connect(lambda: self.dialog_add_org())
###################### slot load ######################
def dialog_add_org(self):
dlg1 = QDialog(self)
dlg1.resize(200,30)
layout = QVBoxLayout(dlg1)
lineEdrpou = QLineEdit("5666667")
lineName = QLineEdit("Yolo")
buttonAdd = QPushButton("Add Data")
layout.addWidget(lineEdrpou)
layout.addWidget(lineName)
layout.addWidget(buttonAdd)
buttonAdd.clicked.connect(lambda: self.add_org(lineEdrpou.text(), lineName.text()))
dlg1.exec_()
# dlg1.close()
def add_org(self, edrpou, name):
new_row = [edrpou, name]
print(new_row)
add_new_organisation(fileEReports, edrpou, name, "")
# MainWindow(dialog_add_org(dlg1.close()))
def message_org_exist(self, edrpou):
dlg2 = QMessageBox(self)
dlg2.setWindowTitle("Attention!")
dlg2.setText("Organisation with Edrpou {0} already exists!".format(edrpou))
button = dlg2.exec_()
if button == QMessageBox.Ok:
print("OK!")
dlg2.close()
def add_new_organisation(filer, inEdrpou, inNewData, inType):
orgsDict = get_orgs_from_file(filer)
lenOrgsDict = len(orgsDict)
itExist = 0
for i in range(lenOrgsDict):
if orgsDict[i]["edrpou"] == inEdrpou:
itExist = itExist + 1
if itExist == 0:
dlg3 = QMessageBox()
dlg3.setWindowTitle("Success!")
dlg3.setText("Organisation {1} with Edrpou {0} was added!".format(inEdrpou, inNewData))
button2 = dlg3.exec_()
if button2 == QMessageBox.Ok:
print("OK!")
dlg3.close()
print("adding new Organisation {0} - {1}".format(inEdrpou, inNewData))
else:
MainWindow(lambda: message_org_exist(inEdrpou))
print("Organisation with this Edrpou already exist")
def main(argv):
app = QApplication(sys.argv)
window = MainWindow()
# print(PyQt5.QtWidgets.QStyleFactory.keys())
# ['Breeze', 'Oxygen', 'QtCurve', 'Windows', 'Fusion']
app.setStyle('Breeze')
window.show()
sys.exit(app.exec_())
##################################################
if __name__ == "__main__":
add_data_to_file(fileEReports)
main(sys.argv)
##################################################
main_window_ui.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui\main_window.ui'
#
# Created by: PyQt5 UI code generator 5.15.7
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(736, 551)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.centralwidget)
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
self.verticalLayoutOrgs = QtWidgets.QVBoxLayout()
self.verticalLayoutOrgs.setSpacing(3)
self.verticalLayoutOrgs.setObjectName("verticalLayoutOrgs")
self.horizontalLayoutOrgs = QtWidgets.QHBoxLayout()
self.horizontalLayoutOrgs.setSizeConstraint(QtWidgets.QLayout.SetDefaultConstraint)
self.horizontalLayoutOrgs.setSpacing(3)
self.horizontalLayoutOrgs.setObjectName("horizontalLayoutOrgs")
self.checkBoxServiced = QtWidgets.QCheckBox(self.centralwidget)
self.checkBoxServiced.setLocale(QtCore.QLocale(QtCore.QLocale.Ukrainian, QtCore.QLocale.Ukraine))
self.checkBoxServiced.setChecked(True)
self.checkBoxServiced.setObjectName("checkBoxServiced")
self.horizontalLayoutOrgs.addWidget(self.checkBoxServiced)
self.checkBoxUr = QtWidgets.QCheckBox(self.centralwidget)
self.checkBoxUr.setChecked(True)
self.checkBoxUr.setObjectName("checkBoxUr")
self.horizontalLayoutOrgs.addWidget(self.checkBoxUr)
self.checkBoxFop = QtWidgets.QCheckBox(self.centralwidget)
self.checkBoxFop.setChecked(True)
self.checkBoxFop.setObjectName("checkBoxFop")
self.horizontalLayoutOrgs.addWidget(self.checkBoxFop)
self.horizontalLayoutOrgs.setStretch(2, 1)
self.verticalLayoutOrgs.addLayout(self.horizontalLayoutOrgs)
spacerItem = QtWidgets.QSpacerItem(0, 8, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
self.verticalLayoutOrgs.addItem(spacerItem)
self.lineEditOrgs = QtWidgets.QLineEdit(self.centralwidget)
self.lineEditOrgs.setObjectName("lineEditOrgs")
self.verticalLayoutOrgs.addWidget(self.lineEditOrgs)
self.tableViewOrgs = QtWidgets.QTableView(self.centralwidget)
self.tableViewOrgs.setLocale(QtCore.QLocale(QtCore.QLocale.Ukrainian, QtCore.QLocale.Ukraine))
self.tableViewOrgs.setAlternatingRowColors(True)
self.tableViewOrgs.setObjectName("tableViewOrgs")
self.verticalLayoutOrgs.addWidget(self.tableViewOrgs)
self.horizontalLayout.addLayout(self.verticalLayoutOrgs)
self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)
self.tabWidget.setObjectName("tabWidget")
self.tab_keys = QtWidgets.QWidget()
self.tab_keys.setObjectName("tab_keys")
self.verticalLayoutKeys = QtWidgets.QVBoxLayout(self.tab_keys)
self.verticalLayoutKeys.setContentsMargins(0, 3, 0, 0)
self.verticalLayoutKeys.setSpacing(3)
self.verticalLayoutKeys.setObjectName("verticalLayoutKeys")
self.lineEditKeys = QtWidgets.QLineEdit(self.tab_keys)
self.lineEditKeys.setObjectName("lineEditKeys")
self.verticalLayoutKeys.addWidget(self.lineEditKeys)
self.tableViewKeys = QtWidgets.QTableView(self.tab_keys)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.tableViewKeys.sizePolicy().hasHeightForWidth())
self.tableViewKeys.setSizePolicy(sizePolicy)
self.tableViewKeys.setLocale(QtCore.QLocale(QtCore.QLocale.Ukrainian, QtCore.QLocale.Ukraine))
self.tableViewKeys.setObjectName("tableViewKeys")
self.verticalLayoutKeys.addWidget(self.tableViewKeys)
self.tabWidget.addTab(self.tab_keys, "")
self.tab_lic = QtWidgets.QWidget()
self.tab_lic.setObjectName("tab_lic")
self.verticalLayoutLic = QtWidgets.QVBoxLayout(self.tab_lic)
self.verticalLayoutLic.setContentsMargins(0, 3, 0, 0)
self.verticalLayoutLic.setSpacing(3)
self.verticalLayoutLic.setObjectName("verticalLayoutLic")
self.lineEditLic = QtWidgets.QLineEdit(self.tab_lic)
self.lineEditLic.setObjectName("lineEditLic")
self.verticalLayoutLic.addWidget(self.lineEditLic)
self.tableViewLic = QtWidgets.QTableView(self.tab_lic)
self.tableViewLic.setLocale(QtCore.QLocale(QtCore.QLocale.Ukrainian, QtCore.QLocale.Ukraine))
self.tableViewLic.setObjectName("tableViewLic")
self.verticalLayoutLic.addWidget(self.tableViewLic)
self.tabWidget.addTab(self.tab_lic, "")
self.tab_acc = QtWidgets.QWidget()
self.tab_acc.setObjectName("tab_acc")
self.verticalLayoutAcc = QtWidgets.QVBoxLayout(self.tab_acc)
self.verticalLayoutAcc.setContentsMargins(0, 3, 0, 0)
self.verticalLayoutAcc.setSpacing(3)
self.verticalLayoutAcc.setObjectName("verticalLayoutAcc")
self.lineEditAcc = QtWidgets.QLineEdit(self.tab_acc)
self.lineEditAcc.setObjectName("lineEditAcc")
self.verticalLayoutAcc.addWidget(self.lineEditAcc)
self.tableViewAcc = QtWidgets.QTableView(self.tab_acc)
self.tableViewAcc.setLocale(QtCore.QLocale(QtCore.QLocale.Ukrainian, QtCore.QLocale.Ukraine))
self.tableViewAcc.setObjectName("tableViewAcc")
self.verticalLayoutAcc.addWidget(self.tableViewAcc)
self.tabWidget.addTab(self.tab_acc, "")
self.horizontalLayout.addWidget(self.tabWidget)
self.horizontalLayout.setStretch(0, 2)
self.horizontalLayout.setStretch(1, 4)
self.horizontalLayout_2.addLayout(self.horizontalLayout)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 736, 21))
self.menubar.setObjectName("menubar")
self.menuFile = QtWidgets.QMenu(self.menubar)
self.menuFile.setObjectName("menuFile")
self.menu_Edit = QtWidgets.QMenu(self.menubar)
self.menu_Edit.setObjectName("menu_Edit")
self.menu_Option = QtWidgets.QMenu(self.menubar)
self.menu_Option.setObjectName("menu_Option")
MainWindow.setMenuBar(self.menubar)
self.toolBar = QtWidgets.QToolBar(MainWindow)
self.toolBar.setObjectName("toolBar")
MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.action_open = QtWidgets.QAction(MainWindow)
self.action_open.setObjectName("action_open")
self.action_open_recent = QtWidgets.QAction(MainWindow)
self.action_open_recent.setObjectName("action_open_recent")
self.action_save = QtWidgets.QAction(MainWindow)
self.action_save.setObjectName("action_save")
self.action_exit = QtWidgets.QAction(MainWindow)
self.action_exit.setObjectName("action_exit")
self.action_pref = QtWidgets.QAction(MainWindow)
self.action_pref.setObjectName("action_pref")
self.action_org_name = QtWidgets.QAction(MainWindow)
self.action_org_name.setObjectName("action_org_name")
self.action_key = QtWidgets.QAction(MainWindow)
self.action_key.setObjectName("action_key")
self.action_copy_edrpou = QtWidgets.QAction(MainWindow)
self.action_copy_edrpou.setObjectName("action_copy_edrpou")
self.action_copy_name = QtWidgets.QAction(MainWindow)
self.action_copy_name.setObjectName("action_copy_name")
self.action_copy_pass_dir = QtWidgets.QAction(MainWindow)
self.action_copy_pass_dir.setObjectName("action_copy_pass_dir")
self.action_copy_pass_stamp = QtWidgets.QAction(MainWindow)
self.action_copy_pass_stamp.setObjectName("action_copy_pass_stamp")
self.action_copy_pass_acc = QtWidgets.QAction(MainWindow)
self.action_copy_pass_acc.setObjectName("action_copy_pass_acc")
self.action_copy_active_line_pass = QtWidgets.QAction(MainWindow)
self.action_copy_active_line_pass.setObjectName("action_copy_active_line_pass")
self.action_add_row_orgs = QtWidgets.QAction(MainWindow)
self.action_add_row_orgs.setObjectName("action_add_row_orgs")
self.action_remove_row_orgs = QtWidgets.QAction(MainWindow)
self.action_remove_row_orgs.setObjectName("action_remove_row_orgs")
self.menuFile.addAction(self.action_open)
self.menuFile.addAction(self.action_open_recent)
self.menuFile.addSeparator()
self.menuFile.addAction(self.action_save)
self.menuFile.addSeparator()
self.menuFile.addAction(self.action_exit)
self.menuFile.addSeparator()
self.menu_Edit.addAction(self.action_add_row_orgs)
self.menu_Edit.addAction(self.action_remove_row_orgs)
self.menu_Edit.addSeparator()
self.menu_Edit.addAction(self.action_org_name)
self.menu_Edit.addAction(self.action_key)
self.menu_Edit.addSeparator()
self.menu_Edit.addAction(self.action_copy_edrpou)
self.menu_Edit.addAction(self.action_copy_name)
self.menu_Edit.addAction(self.action_copy_pass_dir)
self.menu_Edit.addAction(self.action_copy_pass_stamp)
self.menu_Edit.addAction(self.action_copy_pass_acc)
self.menu_Edit.addSeparator()
self.menu_Edit.addAction(self.action_copy_active_line_pass)
self.menu_Option.addAction(self.action_pref)
self.menubar.addAction(self.menuFile.menuAction())
self.menubar.addAction(self.menu_Edit.menuAction())
self.menubar.addAction(self.menu_Option.menuAction())
self.toolBar.addAction(self.action_open)
self.toolBar.addAction(self.action_save)
self.toolBar.addSeparator()
self.toolBar.addAction(self.action_copy_edrpou)
self.toolBar.addAction(self.action_copy_name)
self.toolBar.addAction(self.action_copy_pass_dir)
self.toolBar.addAction(self.action_copy_pass_stamp)
self.toolBar.addAction(self.action_copy_pass_acc)
self.retranslateUi(MainWindow)
self.tabWidget.setCurrentIndex(0)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
MainWindow.setTabOrder(self.checkBoxServiced, self.checkBoxUr)
MainWindow.setTabOrder(self.checkBoxUr, self.checkBoxFop)
MainWindow.setTabOrder(self.checkBoxFop, self.lineEditOrgs)
MainWindow.setTabOrder(self.lineEditOrgs, self.tabWidget)
MainWindow.setTabOrder(self.tabWidget, self.lineEditKeys)
MainWindow.setTabOrder(self.lineEditKeys, self.lineEditLic)
MainWindow.setTabOrder(self.lineEditLic, self.tableViewLic)
MainWindow.setTabOrder(self.tableViewLic, self.lineEditAcc)
MainWindow.setTabOrder(self.lineEditAcc, self.tableViewAcc)
MainWindow.setTabOrder(self.tableViewAcc, self.tableViewOrgs)
MainWindow.setTabOrder(self.tableViewOrgs, self.tableViewKeys)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.centralwidget.setWhatsThis(_translate("MainWindow", "<html><head/><body><p><br/></p></body></html>"))
self.checkBoxServiced.setText(_translate("MainWindow", "Serviced"))
self.checkBoxUr.setText(_translate("MainWindow", "Show Ur"))
self.checkBoxFop.setText(_translate("MainWindow", "Show Fop"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_keys), _translate("MainWindow", "Keys"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_lic), _translate("MainWindow", "Licenses"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_acc), _translate("MainWindow", "Accountants"))
self.menuFile.setTitle(_translate("MainWindow", "&File"))
self.menu_Edit.setTitle(_translate("MainWindow", "&Edit"))
self.menu_Option.setTitle(_translate("MainWindow", "&Option"))
self.toolBar.setWindowTitle(_translate("MainWindow", "toolBar"))
self.action_open.setText(_translate("MainWindow", "&Open"))
self.action_open.setToolTip(_translate("MainWindow", "Open file"))
self.action_open_recent.setText(_translate("MainWindow", "Open recent"))
self.action_open_recent.setToolTip(_translate("MainWindow", "Open recent file"))
self.action_save.setText(_translate("MainWindow", "&Save"))
self.action_save.setToolTip(_translate("MainWindow", "Save file"))
self.action_exit.setText(_translate("MainWindow", "E&xit"))
self.action_pref.setText(_translate("MainWindow", "Preferences"))
self.action_org_name.setText(_translate("MainWindow", "Name and Edrpou"))
self.action_key.setText(_translate("MainWindow", "Key"))
self.action_key.setToolTip(_translate("MainWindow", "Changing Key Data"))
self.action_copy_edrpou.setText(_translate("MainWindow", "Copy Edrpou"))
self.action_copy_name.setText(_translate("MainWindow", "Copy Name"))
self.action_copy_pass_dir.setText(_translate("MainWindow", "Copy Password Dir"))
self.action_copy_pass_stamp.setText(_translate("MainWindow", "Copy Password Stamp"))
self.action_copy_pass_acc.setText(_translate("MainWindow", "Copy Password Accountant"))
self.action_copy_active_line_pass.setText(_translate("MainWindow", "Copy Pass"))
self.action_add_row_orgs.setText(_translate("MainWindow", "Add Row"))
self.action_remove_row_orgs.setText(_translate("MainWindow", "Remove Row"))
======================== edit ========================
I've found a solution to one of my problems. Now the first dialog is closing after second diaog button pressed.
Added this connect signal before dlg1.exec_():
buttonAdd.clicked.connect(dlg1.close_clicked)
dlg1.exec_()
And a small class:
class Dialog(QDialog):
def __init__(self):
QDialog.__init__(self)
def close_clicked(self):
self.close()
And used it
dlg1 = Dialog()
======================== edit 2 ========================
And i've found solution to my other trouble here:
https://www.w3docs.com/snippets/python/typeerror-missing-1-required-positional-argument-self.html
# MainWindow.message_org_exist(inEdrpou)
my_instance = MainWindow()
my_instance.message_org_exist(inEdrpou) # This works
I have a program that dynamically creates tabs with buttons on them, when the user clicks button, I want it to give me the button_id (number that corresponds to the tab index).
I understand that you can do something like tabwidget.currentIndex() to get index of tab being used, but I don't want that as I will eventually have a method that iterates through the number of tabs and access each button without selecting the tabs as shown below.
for i in range(1,self.tabWidget.count()):
self.tabWidget.widget(i).stagematch.click()
For example:
If user clicks 'Clear Text' button on 'Tab 2' then I want it to give me the number 2 back.
How can I accomplish this without using the currentIndex() method for the tabs
Test code:
import sys
from PyQt5 import QtCore, QtWidgets
class TabPage(QtWidgets.QWidget):
def __init__(self, parent=None):
super().__init__(parent)
group = QtWidgets.QGroupBox('Monty Python')
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(group)
grid = QtWidgets.QGridLayout(group)
testbutton = QtWidgets.QPushButton('Clear Text')
grid.addWidget(testbutton, 2, 2)
testbutton.clicked.connect(self.tab_match)
#testbutton.clicked.connect(self.button_id)
def button_id(self):
sender = self.sender()
print(sender.text()) # Gives text of button, i'd like a number that corresponds to the tab# that called it
def tab_match(self,button_id):
#Do something with button ID here
pass
class Window(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.tabs = QtWidgets.QTabWidget()
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.tabs)
button = QtWidgets.QToolButton()
button.setToolTip('Add New Tab')
button.clicked.connect(self.addNewTab)
button.setIcon(self.style().standardIcon(
QtWidgets.QStyle.SP_DialogYesButton))
self.tabs.setCornerWidget(button, QtCore.Qt.TopRightCorner)
self.addNewTab()
def addNewTab(self):
text = 'Tab %d' % (self.tabs.count() + 1)
self.tabs.addTab(TabPage(self.tabs), text)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = Window()
window.setGeometry(600, 100, 300, 200)
window.show()
sys.exit(app.exec_())
Try it:
import sys
from PyQt5 import QtCore, QtWidgets
class TabPage(QtWidgets.QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.parent = parent # +
self.button_id = 0 # +
group = QtWidgets.QGroupBox('Monty Python')
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(group)
grid = QtWidgets.QGridLayout(group)
testbutton = QtWidgets.QPushButton('Clear Text')
grid.addWidget(testbutton, 2, 2)
testbutton.clicked.connect(self.tab_match)
self.parent.currentChanged.connect(self.qtabwidget_currentchanged) # +
def tab_match(self):
#Do something with button ID here
print("\ndef tab_match: button_id-> {}".format(self.button_id)) # +
#QtCore.pyqtSlot(int)
def qtabwidget_currentchanged(self, index): # +
self.button_id = index
class Window(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.tabs = QtWidgets.QTabWidget()
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.tabs)
button = QtWidgets.QToolButton()
button.setToolTip('Add New Tab')
button.clicked.connect(self.addNewTab)
button.setIcon(self.style().standardIcon(
QtWidgets.QStyle.SP_DialogYesButton))
self.tabs.setCornerWidget(button, QtCore.Qt.TopRightCorner)
self.button_id = 0
self.addNewTab()
def addNewTab(self):
text = 'Tab %d' % (self.tabs.count() + 1)
self.tabs.addTab(TabPage(self.tabs), text)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = Window()
window.setGeometry(600, 100, 300, 200)
window.show()
sys.exit(app.exec_())
I am using PyQt5 to create a GUI program.
I have a problem when creating a label beside the QComboBox.
If I didnt create a label beside the QComboBox , it would look like the picture down below.
But if I added the label it would be like this :
The selection list just moved down a little bit automatically.
How can I do to make it be align to the label at the left-hand side?
(I mean just beside the CASE TYPE)
(I comment the critical part in my code)
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5 import QtWidgets
import xml.etree.cElementTree as ET
class App(QMainWindow):
def __init__(self,parent=None):
super().__init__()
self.title = "Automation"
self.left = 10
self.top = 10
self.width = 400
self.height = 200
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
# Create textbox
self.textbox = QLineEdit(self)
self.textbox.move(80, 20)
#self.textbox.resize(50,40)
self.textbox2 = QLineEdit(self)
self.textbox2.move(80, 80)
#self.textbox2.resize(50,40)
# Create text beside editor
wid1 = QWidget(self)
self.setCentralWidget(wid1)
mytext = QFormLayout()
mytext.addRow("CASE INDEX",self.textbox)
mytext.addRow("CASE TYPE",self.textbox2)
wid1.setLayout(mytext)
#################### Critical Part #######################
self.CB = QComboBox()
self.CB.addItems(["RvR","Turntable","Fixrate"])
self.CB.currentIndexChanged.connect(self.selectionchange)
label = QLabel("CASE TYPE")
mytext.addRow(label,self.CB) # this one makes the list shift down a little bit
mytext.addWidget(self.CB)
wid1.setLayout(mytext)
##########################################################
# Create a button in the window
self.button = QPushButton('Show text', self)
self.button.move(20,150)
# connect button to function on_click
self.button.clicked.connect(self.on_click)
self.center()
self.show()
#pyqtSlot()
def on_click(self):
textboxValue = self.textbox.text()
textboxValue2 = self.textbox2.text()
QMessageBox.question(self, 'Message - pythonspot.com', "You typed: "+ textboxValue + " , second msg is: " + textboxValue2, QMessageBox.Ok, QMessageBox.Ok)
print(textboxValue)
self.textbox.setText("")
self.textbox2.setText("")
def center(self):
qr = self.frameGeometry()
cp = QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
def selectionchange(self,i):
print ("Items in the list are :")
for count in range(self.CB.count()):
print (self.CB.itemText(count))
print ("Current index",i,"selection changed ",self.CB.currentText())
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
Please , I need your help.
Thanks.
Try it:
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5 import QtWidgets
import xml.etree.cElementTree as ET
class App(QMainWindow):
def __init__(self,parent=None):
super().__init__()
self.title = "Automation"
self.left = 10
self.top = 10
self.width = 400
self.height = 200
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
# Create textbox
self.textbox = QLineEdit(self)
# self.textbox.move(80, 20)
#self.textbox.resize(50,40)
self.textbox2 = QLineEdit(self)
# self.textbox2.move(80, 80)
#self.textbox2.resize(50,40)
# Create text beside editor
wid1 = QWidget(self)
self.setCentralWidget(wid1)
mytext = QFormLayout()
mytext.addRow("CASE INDEX", self.textbox)
mytext.addRow("CASE TYPE", self.textbox2)
# wid1.setLayout(mytext)
#################### Critical Part #######################
self.CB = QComboBox()
self.CB.addItems(["RvR","Turntable","Fixrate"])
self.CB.currentIndexChanged.connect(self.selectionchange)
label = QLabel("CASE TYPE")
mytext.addRow(label, self.CB) # this one makes the list shift down a little bit
# mytext.addWidget(self.CB)
# wid1.setLayout(mytext)
##########################################################
# Create a button in the window
self.button = QPushButton('Show text', self)
# self.button.move(20,150)
# connect button to function on_click
self.button.clicked.connect(self.on_click)
layoutV = QVBoxLayout(wid1) # + wid1 <<<========
layoutV.addLayout(mytext) # +
layoutV.addWidget(self.button, alignment=Qt.AlignLeft) # +
self.center()
self.show()
#pyqtSlot()
def on_click(self):
textboxValue = self.textbox.text()
textboxValue2 = self.textbox2.text()
QMessageBox.question(self, 'Message - pythonspot.com', "You typed: "+ textboxValue + " , second msg is: " + textboxValue2, QMessageBox.Ok, QMessageBox.Ok)
print(textboxValue)
self.textbox.setText("")
self.textbox2.setText("")
def center(self):
qr = self.frameGeometry()
cp = QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
def selectionchange(self,i):
print ("Items in the list are :")
for count in range(self.CB.count()):
print (self.CB.itemText(count))
print ("Current index",i,"selection changed ",self.CB.currentText())
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
I am new to PyQt, I am trying to implement slider in PyQt4, but i don't know why code code is not generating any output.
what i want is, create 3 slider to change 3 values dynamically.
Here i am resizing font size of text "hue", "sat", "val".
Is there is any good source to learn slider in PyQt?
here is my code
PyQt4Slider.py
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class Window(QWidget):
def __init__(self):
super(Window, self).__init__()
self.setGeometry(50,50,500,300)
self.setWindowTiltle("HSV")
self.home()
def home(self):
#hue = 100
#sat = 100
#val = 100
layout = QVBoxLayout()
self.l1 = QLabel("hue")
self.l2 = QLabel("sat")
self.l3 = QLabel("val")
self.l1.setAlignment(Qt.AlignCenter)
self.l2.setAlignment(Qt.AlignCenter)
self.l3.setAlignment(Qt.AlignCenter)
layout.addWidget(self.l1)
layout.addWidget(self.l1)
layout.addWidget(self.l1)
self.sl = QSlider(Qt.Horizontal)
self.s2 = QSlider(Qt.Horizontal)
self.s3 = QSlider(Qt.Horizontal)
self.sl.setMinimum(0)
self.sl.setMaximum(179)
self.sl.setValue(20)
self.sl.setTickPosition(QSlider.TicksBelow)
self.sl.setTickInterval(5)
self.s2.setMinimum(0)
self.s2.setMaximum(255)
self.s2.setValue(100)
self.s2.setTickPosition(QSlider.TicksBelow)
self.s2.setTickInterval(5)
self.s3.setMinimum(0)
self.s3.setMaximum(255)
self.s3.setValue(100)
self.s3.setTickPosition(QSlider.TicksBelow)
self.s3.setTickInterval(5)
layout.addWidget(self.s1)
self.sl.valueChanged.connect(self.valuechange)
layout.addWidget(self.s2)
self.s2.valueChanged.connect(self.valuechange)
layout.addWidget(self.s3)
self.s3.valueChanged.connect(self.valuechange)
self.setLayout(layout)
def valuechange(self):
sizel1 = self.sl.value()
self.l1.setFont("Arial",sizel1)
sizel2 = self.sl.value()
self.l2.setFont("Arial", sizel2)
sizel2 = self.sl.value()
self.l2.setFont("Arial", sizel2)
def main():
app = QApplication(sys.argv)
ex = Window()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
here is what i am getting after running code
Ran 0 tests in 0.000s
OK
Process finished with exit code 0
Empty test suite.
Most of the problems in your script are caused by typos. Here is a fixed version that should work okay:
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class Window(QWidget):
def __init__(self):
super(Window, self).__init__()
self.setGeometry(50,50,500,300)
self.setWindowTitle("HSV")
self.home()
def home(self):
layout = QVBoxLayout()
self.l1 = QLabel("hue")
self.l2 = QLabel("sat")
self.l3 = QLabel("val")
self.l1.setAlignment(Qt.AlignCenter)
self.l2.setAlignment(Qt.AlignCenter)
self.l3.setAlignment(Qt.AlignCenter)
layout.addWidget(self.l1)
layout.addWidget(self.l2)
layout.addWidget(self.l3)
self.s1 = QSlider(Qt.Horizontal)
self.s2 = QSlider(Qt.Horizontal)
self.s3 = QSlider(Qt.Horizontal)
self.s1.setMinimum(0)
self.s1.setMaximum(179)
self.s1.setValue(20)
self.s1.setTickPosition(QSlider.TicksBelow)
self.s1.setTickInterval(5)
self.s2.setMinimum(0)
self.s2.setMaximum(255)
self.s2.setValue(100)
self.s2.setTickPosition(QSlider.TicksBelow)
self.s2.setTickInterval(5)
self.s3.setMinimum(0)
self.s3.setMaximum(255)
self.s3.setValue(100)
self.s3.setTickPosition(QSlider.TicksBelow)
self.s3.setTickInterval(5)
layout.addWidget(self.s1)
self.s1.valueChanged.connect(self.valuechange)
layout.addWidget(self.s2)
self.s2.valueChanged.connect(self.valuechange)
layout.addWidget(self.s3)
self.s3.valueChanged.connect(self.valuechange)
self.setLayout(layout)
# set the initial fonts
self.valuechange()
def valuechange(self):
sizel1 = self.s1.value()
self.l1.setFont(QFont("Arial", sizel1))
sizel2 = self.s2.value()
self.l2.setFont(QFont("Arial", sizel2))
sizel3 = self.s3.value()
self.l3.setFont(QFont("Arial", sizel3))
def main():
app = QApplication(sys.argv)
ex = Window()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Need some advice on how to retrieve the directory path for a selected folder and set it on the LineEdit.
I have the following simple GUI
If I clicked the toolButton (the button inside the red-circle), then a dialog window would pop up. Then we could navigate to select the desired folder. I wish that I could pass the path (in string) to the selected folder to the lineEdit box next to the button, once the user clicks Select Folder. However, I could not figure out how to do that. So far here is my code:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_TestQFileDialog(object):
def _open_file_dialog(self): # a function to open the dialog window
result = str(QtWidgets.QFileDialog.getExistingDirectory())
print(result)
return result
def setupUi(self, TestQFileDialog):
TestQFileDialog.setObjectName("TestQFileDialog")
TestQFileDialog.resize(240, 320)
self.toolButtonOpenDialog = QtWidgets.QToolButton(TestQFileDialog)
self.toolButtonOpenDialog.setGeometry(QtCore.QRect(210, 10, 25, 19))
self.toolButtonOpenDialog.setObjectName("toolButtonOpenDialog")
directory = self.toolButtonOpenDialog.clicked.connect(self._open_file_dialog)
self.lineEdit = QtWidgets.QLineEdit(TestQFileDialog)
self.lineEdit.setEnabled(False)
self.lineEdit.setGeometry(QtCore.QRect(10, 10, 191, 20))
self.lineEdit.setObjectName("lineEdit")
self.lineEdit.setText('{}'.format(directory))
self.retranslateUi(TestQFileDialog)
QtCore.QMetaObject.connectSlotsByName(TestQFileDialog)
def retranslateUi(self, TestQFileDialog):
_translate = QtCore.QCoreApplication.translate
TestQFileDialog.setWindowTitle(_translate("TestQFileDialog", "Dialog"))
self.toolButtonOpenDialog.setText(_translate("TestQFileDialog", "..."))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
TestQFileDialog = QtWidgets.QDialog()
ui = Ui_TestQFileDialog()
ui.setupUi(TestQFileDialog)
TestQFileDialog.show()
sys.exit(app.exec_())
Tried to include print in the _open_file_dialog function, and it printed the directory path. However, it was not returned and kept in the directory variable.
Any advice will be much appreciated.
Thanks and regards,
Arnold
Found the answer, the .setText method should be included in the _open_file_dialog function.
Therefore, the final code would look like this:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_TestQFileDialog(object):
def _open_file_dialog(self):
directory = str(QtWidgets.QFileDialog.getExistingDirectory())
self.lineEdit.setText('{}'.format(directory))
def _set_text(self, text):
return text
def setupUi(self, TestQFileDialog):
TestQFileDialog.setObjectName("TestQFileDialog")
TestQFileDialog.resize(240, 320)
self.toolButtonOpenDialog = QtWidgets.QToolButton(TestQFileDialog)
self.toolButtonOpenDialog.setGeometry(QtCore.QRect(210, 10, 25, 19))
self.toolButtonOpenDialog.setObjectName("toolButtonOpenDialog")
self.toolButtonOpenDialog.clicked.connect(self._open_file_dialog)
self.lineEdit = QtWidgets.QLineEdit(TestQFileDialog)
self.lineEdit.setEnabled(False)
self.lineEdit.setGeometry(QtCore.QRect(10, 10, 191, 20))
self.lineEdit.setObjectName("lineEdit")
self.retranslateUi(TestQFileDialog)
QtCore.QMetaObject.connectSlotsByName(TestQFileDialog)
def retranslateUi(self, TestQFileDialog):
_translate = QtCore.QCoreApplication.translate
TestQFileDialog.setWindowTitle(_translate("TestQFileDialog", "Dialog"))
self.toolButtonOpenDialog.setText(_translate("TestQFileDialog", "..."))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
TestQFileDialog = QtWidgets.QDialog()
ui = Ui_TestQFileDialog()
ui.setupUi(TestQFileDialog)
TestQFileDialog.show()
sys.exit(app.exec_())
With QWidget
from PyQt5.QtWidgets import QWidget, QFileDialog,QDialog,QToolButton,QLineEdit,QVBoxLayout ,QGridLayout
class Ui_TestQFileDialog(QWidget):
def __init__(self,parent=None) -> None:
super(Ui_TestQFileDialog,self).__init__(parent)
self.setupUi()
self.show()
def _open_file_dialog(self,lineeditr):
directory = str(QFileDialog.getExistingDirectory())
lineeditr.setText('{}'.format(directory))
def _open_file_dialog1(self):
directory = str(QFileDialog.getExistingDirectory())
self.lineEdit1.setText('{}'.format(directory))
def _set_text(self, text):
return text
def setupUi(self):
# ------------------------- first set ------------------------------------------------------
TestQFileDialog = QDialog()
# TestQFileDialog.setObjectName("TestQFileDialog")
# TestQFileDialog.resize(240, 320)
self.toolButtonOpenDialog = QToolButton(TestQFileDialog)
# self.toolButtonOpenDialog.setGeometry(QtCore.QRect(210, 10, 25, 19))
# self.toolButtonOpenDialog.setObjectName("toolButtonOpenDialog")
self.lineEdit = QLineEdit(TestQFileDialog)
self.lineEdit.setEnabled(False)
# self.lineEdit.setGeometry(QtCore.QRect(10, 10, 191, 20))
# self.lineEdit.setObjectName("lineEdit")
self.lineEdit.textChanged.connect(self.prine_la)
self.toolButtonOpenDialog.clicked.connect(lambda: (self._open_file_dialog(self.lineEdit)))
# ----------------------------- second set --------------------------------------------------------
TestQFileDialog1 = QDialog()
# TestQFileDialog1.setObjectName("TestQFileDialog")
# TestQFileDialog1.resize(240, 320)
self.toolButtonOpenDialog1 = QToolButton(TestQFileDialog1)
# self.toolButtonOpenDialog1.setGeometry(QtCore.QRect(210, 10, 25, 19))
# self.toolButtonOpenDialog1.setObjectName("toolButtonOpenDialog")
self.lineEdit1 = QLineEdit(TestQFileDialog1)
self.lineEdit1.setEnabled(False)
self.lineEdit1.setPlaceholderText("Enter the gain value in between 0.0 to 23.05934920")
# self.lineEdit1.setGeometry(QtCore.QRect(10, 10, 191, 20))
# self.lineEdit1.setObjectName("lineEdit1")
self.toolButtonOpenDialog1.clicked.connect(lambda: (self._open_file_dialog(self.lineEdit1)))
self.retranslateUi(TestQFileDialog,self.toolButtonOpenDialog,"TestQFileDialog","data")
self.retranslateUi(TestQFileDialog1,self.toolButtonOpenDialog1,"TestQFileDialog1","data1")
QtCore.QMetaObject.connectSlotsByName(TestQFileDialog)
QtCore.QMetaObject.connectSlotsByName(TestQFileDialog1)
grid_layout = QGridLayout()
grid_layout.addWidget(self.lineEdit,0,0)
grid_layout.addWidget(self.toolButtonOpenDialog,0,1)
grid_layout.addWidget(self.lineEdit1,1,0)
grid_layout.addWidget(self.toolButtonOpenDialog1,1,1)
ve_box= QVBoxLayout()
# ve_box.addWidget(self.lineEdit)
# ve_box.addWidget(self.toolButtonOpenDialog)
# ve_box.addWidget(self.lineEdit1)
# ve_box.addWidget(self.toolButtonOpenDialog1)
ve_box.addLayout(grid_layout)
self.setLayout(ve_box)
def prine_la(self):
print(self.lineEdit.text())
def retranslateUi(self, TestQFileDialog,tool,dialogue:str,d: str):
_translate = QtCore.QCoreApplication.translate
TestQFileDialog.setWindowTitle(_translate(dialogue, d))
tool.setText(_translate(dialogue, "..."))
print("ANR .S")
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
ui = Ui_TestQFileDialog()
sys.exit(app.exec_())