PyQt5 Retrieve Folder Directory and Set It in lineEdit - python-3.x

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

Related

Python PyQt5 Terminal Command execution problem on a button click

I'm trying to create an application, that can execute an embedded Terminal command when ever the button is clicked. The actual problem occurs when i click the button and nothing happens.
I have two scripts one has a terminal widget and the other has the main GUI. Any Help, would be highly appreciated.
That's first Script
import sys
from PyQt5 import QtCore, QtWidgets
class EmbTerminal(QtWidgets.QWidget):
def __init__(self, parent=None):
super(EmbTerminal, self).__init__(parent)
self._process = []
self.start_process('urxvt',['-embed', str(int(self.winId())),"-e","tmux"])
def start_process(self,prog,options):
child = QtCore.QProcess(self)
self._process.append(child)
child.start(prog,options)
def run_command(self, command = "ls" ):
program = "tmux"
options = []
options.extend(["send-keys"])
options.extend([command])
options.extend(["Enter"])
self.start_process(program, options)
That's Second Script
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(745, 496)
self.tabWidget = QtWidgets.QTabWidget(Dialog)
self.tabWidget.setGeometry(QtCore.QRect(100, 190, 561, 261))
self.tabWidget.setObjectName("tabWidget")
self.tab = QtWidgets.QWidget()
self.tab.setObjectName("tab")
self.tabWidget.addTab(EmbTerminal(), "Terminal")
self.tab_2 = QtWidgets.QWidget()
self.tab_2.setObjectName("tab_2")
self.tabWidget.addTab(self.tab_2, "")
self.pushButton = QtWidgets.QPushButton(Dialog)
self.pushButton.setGeometry(QtCore.QRect(280, 70, 211, 71))
self.pushButton.setObjectName("pushButton")
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
self.pushButton.clicked.connect(lambda: EmbTerminal.run_command(EmbTerminal(), "ls"))
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("Dialog", "Tab 1"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("Dialog", "Tab 2"))
self.pushButton.setText(_translate("Dialog", "ls"))
from terminal5 import EmbTerminal
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Dialog = QtWidgets.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec_())
You should consider the following:
You should not modify the code generated by Qt Designer (unless you understand its logic)
Do not implement the logic in the class generated by Qt Designer, it is advisable to create a new class that inherits from the appropriate widget and use the other class to fill it.
In your case the problem is that the EmbTerminal() object in lambda: EmbTerminal.run_command(EmbTerminal(), "ls") only exists while the lambda is running, but the lambda runs for a very short time causing the command not to be sent causing the error.
Considering the above, the solution is:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(745, 496)
self.tabWidget = QtWidgets.QTabWidget(Dialog)
self.tabWidget.setGeometry(QtCore.QRect(100, 190, 561, 261))
self.tabWidget.setObjectName("tabWidget")
self.pushButton = QtWidgets.QPushButton(Dialog)
self.pushButton.setGeometry(QtCore.QRect(280, 70, 211, 71))
self.pushButton.setObjectName("pushButton")
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.pushButton.setText(_translate("Dialog", "ls"))
from terminal5 import EmbTerminal
class Dialog(QtWidgets.QDialog, Ui_Dialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setupUi(self)
self.terminal = EmbTerminal()
self.tabWidget.addTab(self.terminal, "Terminal")
self.pushButton.clicked.connect(self.on_clicked)
#QtCore.pyqtSlot()
def on_clicked(self):
self.terminal.run_command("ls")
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = Dialog()
w.show()
sys.exit(app.exec_())
On the other hand if you are only going to send commands then it is not necessary to store the QProcess, instead use QProcess: startDetached and make run_command a classmethod:
class EmbTerminal(QtWidgets.QWidget):
# ...
#staticmethod
def run_command(command = "ls" ):
program = "tmux"
options = []
options.extend(["send-keys"])
options.extend([command])
options.extend(["Enter"])
QtCore.QProcess.startDetached(program, options)

How to remove all widgets within a QGroupBox in PyQt5?

In my program there is a QGroupBox displayed that has many QPushButton's within it. During the execution of the program, the user can click a button outside of the QGroupBox and all of the buttons within it will be removed or hidden. Problem is that I can't seem to find a way to do this to the buttons directly or by clearing the QGroupBox.
I have already tried deleteLater on the buttons but that didn't work. I then tried clearing the layout of the QGroupBox but that didn't work either. Here is some code I just wrote up that has a the same problem:
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
import random
class UI_Dialog(object):
def addButtons(self,looping):
# Code to remove the previous QPushButton's goes here.
placement = -100
for i in range(looping):
currentName = 'btn' + str(i)
placement = placement + 110
self.btnB = QtWidgets.QPushButton(self.groupBox)
self.btnB.setGeometry(QtCore.QRect(10+placement, 30+placement, 100, 100))
self.btnB.show()
self.btnB.setObjectName(currentName)
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(1300, 800)
self.btnA = QtWidgets.QPushButton(Dialog)
self.btnA.setGeometry(QtCore.QRect(10, 80, 101, 131))
self.btnA.setObjectName("btn1")
self.btnA.clicked.connect(self.pushed)
self.formLayout = QtWidgets.QFormLayout()
self.groupBox = QtWidgets.QGroupBox("Results")
self.groupBox.setLayout(self.formLayout)
self.resultScrollArea = QtWidgets.QScrollArea(Dialog)
self.resultScrollArea.setWidget(self.groupBox)
self.resultScrollArea.setGeometry(QtCore.QRect(20, 220, 1011, 531))
self.resultScrollArea.setWidgetResizable(True)
self.resultScrollArea.setObjectName("resultScrollArea")
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def pushed(self):
unkownLength = random.randint(1,20)
self.addButtons(unkownLength)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Example Program"))
self.btnA.setText(_translate("Dialog", "Push Button"))
app = QtWidgets.QApplication(sys.argv)
Dialog = QtWidgets.QDialog()
ui = UI_Dialog()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec_())
There are things here that probably don't make sense like the window size, the multiple function calls or it being a Dialog window instead of a QMainWindow. However, in the context of the actual program they do make sense so just ignore that, I know it's inefficient. Also the whole point of the unkownLength variable is to emulate that in the actual program, the number of buttons generated will be determined by user input. The buttons must also not be there at the start so that is why they're created with a button click. When the button is clicked again it should remove or hide all the buttons it created before. Any ideas?
Taking advantage that the buttons are children of the QGroupBox we can get the buttons using findChildren() to use deleteLater():
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
import random
class UI_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(1300, 800)
self.btnA = QtWidgets.QPushButton(Dialog)
self.btnA.setGeometry(QtCore.QRect(10, 80, 101, 131))
self.btnA.setObjectName("btn1")
self.formLayout = QtWidgets.QFormLayout()
self.groupBox = QtWidgets.QGroupBox("Results")
self.groupBox.setLayout(self.formLayout)
self.resultScrollArea = QtWidgets.QScrollArea(Dialog)
self.resultScrollArea.setWidget(self.groupBox)
self.resultScrollArea.setGeometry(QtCore.QRect(20, 220, 1011, 531))
self.resultScrollArea.setWidgetResizable(True)
self.resultScrollArea.setObjectName("resultScrollArea")
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Example Program"))
self.btnA.setText(_translate("Dialog", "Push Button"))
class Dialog(QtWidgets.QDialog, UI_Dialog):
def __init__(self, parent=None):
super(Dialog, self).__init__(parent)
self.setupUi(self)
self.btnA.clicked.connect(self.pushed)
#QtCore.pyqtSlot()
def pushed(self):
unkownLength = random.randint(1, 20)
self.addButtons(unkownLength)
def addButtons(self, looping):
for button in self.groupBox.findChildren(QtWidgets.QPushButton):
button.deleteLater()
placement = -100
pos = QtCore.QPoint(20, 40)
for i in range(looping):
currentName = "btn" + str(i)
self.btnB = QtWidgets.QPushButton(
self.groupBox, objectName=currentName
)
self.btnB.setGeometry(QtCore.QRect(pos, QtCore.QSize(100, 100)))
pos += QtCore.QPoint(110, 110)
self.btnB.show()
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
w = Dialog()
w.show()
sys.exit(app.exec_())

Python - showing next Tab by pressing a button

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

in PyQt5 move tab page widgets to desired tab page dynamically using tab index

In python, using PyQt5 while moving from one tab page to another, need to move the widgets from source page to destination tab page using the index number.
I was trying the following code. But No idea. Can anybody guide me. Thanks
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(1251, 645)
self.tabWidget = QtWidgets.QTabWidget(Form)
self.tabWidget.setGeometry(QtCore.QRect(40, 40, 1161, 571))
self.tabWidget.setObjectName("tabWidget")
self.tab_1 = QtWidgets.QWidget()
self.tab_1.setObjectName("tab_1")
self.tabWidget.addTab(self.tab_1, "")
self.tab_2 = QtWidgets.QWidget()
self.tab_2.setObjectName("tab_2")
self.tabWidget.addTab(self.tab_2, "")
self.tabWidget.currentChanged.connect(self.header_Tab_Changed)
global TAB_OPTION
if TAB_OPTION==0:
self.pushButton = QtWidgets.QPushButton(self.tab_1)
self.pushButton.setGeometry(QtCore.QRect(290, 130, 631, 161))
self.pushButton.setObjectName("pushButton")
elif TAB_OPTION==1:
self.pushButton = QtWidgets.QPushButton(self.tab_2)
self.pushButton.setGeometry(QtCore.QRect(100, 100, 431, 61))
self.pushButton.setObjectName("pushButton")
self.retranslateUi(Form)
self.tabWidget.setCurrentIndex(0)
QtCore.QMetaObject.connectSlotsByName(Form)
def header_Tab_Changed(self,index):
global TAB_OPTION
TAB_OPTION=index
#I need to move the push button between tabs ????????????????
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_1), _translate("Form", "First-Page"))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("Form", "Second-Page"))
self.pushButton.setText(_translate("Form", "PushButton"))
if __name__ == "__main__":
import sys
global TAB_OPTION
TAB_OPTION=0
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_Form()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())

Copy/Save PyQt5 Listbox items in a text file python

After several clicks of Add button, it adds items to the listbox. I wish to save all the items from the listbox to a textfile with the save button.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(400, 300)
self.listView = QtWidgets.QListWidget(Dialog)
self.listView.setGeometry(QtCore.QRect(120, 40, 256, 192))
self.listView.setObjectName("listView")
self.AddButton = QtWidgets.QPushButton(Dialog)
self.AddButton.setGeometry(QtCore.QRect(20, 80, 75, 41))
self.AddButton.setObjectName("AddButton")
self.SaveButton = QtWidgets.QPushButton(Dialog)
self.SaveButton.setGeometry(QtCore.QRect(20, 140, 75, 41))
self.SaveButton.setObjectName("SaveButton")
self.AddButton.clicked.connect(self.ADD)
self.SaveButton.clicked.connect(self.SAVE)
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.AddButton.setText(_translate("Dialog", "Add to List"))
self.SaveButton.setText(_translate("Dialog", "Save"))
def ADD(self):
self.listView.addItem("SAMPLE STRING")
def SAVE(self):
s = open('textfile.txt','a')
for items in self.listView():
s.write(item)
s.close()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Dialog = QtWidgets.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec_())
but the code under the def SAVE(self): doesn't work.
self.listView is an object and not callable by self.listView(). I suppose you want to save the items's text. You can get it and all other data of the items from the listViews model:
def SAVE(self):
with open('textfile.txt','a') as s:
for i in range(self.listView.model().rowCount()):
text = self.listView.model().data(self.listView.model().index(i))
# print(i, text)
s.write(text)
or ask for the text() of the items:
def SAVE(self):
with open('textfile.txt','a') as s:
for i in range(self.listView.model().rowCount()):
text = self.listView.item(i).text()
# print(i, text)
s.write(text)

Resources