Buttons in PyQT5 using python - python-3.x

I created a back button in new window and next button in main window. After I clicked the next button to show a new window, it was successfully hides the current main window but when I clicked back button on the new window, the application automatically closes itself. Any idea?
The code in first mainWindow.py file:
from PyQt5 import QtCore, QtGui, QtWidgets
try:
from secondWindow import Ui_SecondWindow
except:
import secondWindow
class Ui_firstWindow(object):
def secondWindow(self):
self.window = QtWidgets.QMainWindow()
self.ui = Ui_SecondWindow()
self.ui.setupUi(self.window)
self.window.show()
if self.window.show():
self.hide
def setupUi(self, firstWindow):
firstWindow.setObjectName("firstWindow")
firstWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(firstWindow)
self.centralwidget.setObjectName("centralwidget")
self.btn_next = QtWidgets.QPushButton(self.centralwidget)
self.btn_next.setGeometry(QtCore.QRect(160, 100, 521, 291))
self.btn_next.setObjectName("btn_next")
######To Open second window###########
self.btn_next.clicked.connect(self.secondWindow)
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(360, 420, 151, 16))
self.label.setStyleSheet("font: 11pt \"MS Shell Dlg 2\";")
self.label.setObjectName("label")
firstWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(firstWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
self.menubar.setObjectName("menubar")
firstWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(firstWindow)
self.statusbar.setObjectName("statusbar")
firstWindow.setStatusBar(self.statusbar)
self.retranslateUi(firstWindow)
QtCore.QMetaObject.connectSlotsByName(firstWindow)
def retranslateUi(self, firstWindow):
_translate = QtCore.QCoreApplication.translate
firstWindow.setWindowTitle(_translate("firstWindow", "MainWindow"))
self.btn_next.setText(_translate("firstWindow", "Next"))
self.label.setText(_translate("firstWindow", "First Window"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
firstWindow = QtWidgets.QMainWindow()
ui = Ui_firstWindow()
ui.setupUi(firstWindow)
firstWindow.show()
sys.exit(app.exec_())
The codes in second secondWindow.py file:
from PyQt5 import QtCore, QtGui, QtWidgets
try:
from mainWindow import Ui_firstWindow
except:
import mainWindow
class Ui_SecondWindow(object):
###function to go back the first window######
# #pyqtSlot()
def openBackFirstWindow(self):
self.window = QtWidgets.QMainWindow()
self.ui = Ui_firstWindow()
self.ui.setupUi(self.window)
self.window.show()
if self.window.show():
self.hide
def setupUi(self, SecondWindow):
SecondWindow.setObjectName("SecondWindow")
SecondWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(SecondWindow)
self.centralwidget.setObjectName("centralwidget")
self.btn_back = QtWidgets.QPushButton(self.centralwidget)
self.btn_back.setGeometry(QtCore.QRect(220, 100, 401, 281))
self.btn_back.setObjectName("btn_back")
###To go back to first windo######
self.btn_back.clicked.connect(self.openBackFirstWindow)
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(370, 440, 151, 16))
self.label.setStyleSheet("font: 11pt \"MS Shell Dlg 2\";")
self.label.setObjectName("label")
SecondWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(SecondWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
self.menubar.setObjectName("menubar")
SecondWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(SecondWindow)
self.statusbar.setObjectName("statusbar")
SecondWindow.setStatusBar(self.statusbar)
self.retranslateUi(SecondWindow)
QtCore.QMetaObject.connectSlotsByName(SecondWindow)
def retranslateUi(self, SecondWindow):
_translate = QtCore.QCoreApplication.translate
SecondWindow.setWindowTitle(_translate("SecondWindow", "MainWindow"))
self.btn_back.setText(_translate("SecondWindow", "Back"))
self.label.setText(_translate("SecondWindow", "Second Window"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
SecondWindow = QtWidgets.QMainWindow()
ui = Ui_SecondWindow()
ui.setupUi(SecondWindow)
SecondWindow.show()
sys.exit(app.exec_())
When i clicked the back button in second window, the application stopped working and exits itself. Any idea?

Do not modify the code generated by Qt Designer but create another class that inherits
from the appropriate widget and use the initial class to fill it.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_firstWindow(object):
def setupUi(self, firstWindow):
firstWindow.setObjectName("firstWindow")
firstWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(firstWindow)
self.centralwidget.setObjectName("centralwidget")
self.btn_next = QtWidgets.QPushButton(self.centralwidget)
self.btn_next.setGeometry(QtCore.QRect(160, 100, 521, 291))
self.btn_next.setObjectName("btn_next")
# ######To Open second window###########
# self.btn_next.clicked.connect(self.secondWindow)
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(360, 420, 151, 16))
self.label.setStyleSheet("font: 11pt \"MS Shell Dlg 2\";")
self.label.setObjectName("label")
firstWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(firstWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
self.menubar.setObjectName("menubar")
firstWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(firstWindow)
self.statusbar.setObjectName("statusbar")
firstWindow.setStatusBar(self.statusbar)
self.retranslateUi(firstWindow)
QtCore.QMetaObject.connectSlotsByName(firstWindow)
def retranslateUi(self, firstWindow):
_translate = QtCore.QCoreApplication.translate
firstWindow.setWindowTitle(_translate("firstWindow", "MainWindow"))
self.btn_next.setText(_translate("firstWindow", "Next"))
self.label.setText(_translate("firstWindow", "First Window"))
class Ui_SecondWindow(object):
def setupUi(self, SecondWindow):
SecondWindow.setObjectName("SecondWindow")
SecondWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(SecondWindow)
self.centralwidget.setObjectName("centralwidget")
self.btn_back = QtWidgets.QPushButton(self.centralwidget)
self.btn_back.setGeometry(QtCore.QRect(220, 100, 401, 281))
self.btn_back.setObjectName("btn_back")
# ###To go back to first windo######
# self.btn_back.clicked.connect(self.openBackFirstWindow)
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(370, 440, 151, 16))
self.label.setStyleSheet("font: 11pt \"MS Shell Dlg 2\";")
self.label.setObjectName("label")
SecondWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(SecondWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
self.menubar.setObjectName("menubar")
SecondWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(SecondWindow)
self.statusbar.setObjectName("statusbar")
SecondWindow.setStatusBar(self.statusbar)
self.retranslateUi(SecondWindow)
QtCore.QMetaObject.connectSlotsByName(SecondWindow)
def retranslateUi(self, SecondWindow):
_translate = QtCore.QCoreApplication.translate
SecondWindow.setWindowTitle(_translate("SecondWindow", "MainWindow"))
self.btn_back.setText(_translate("SecondWindow", "Back"))
self.label.setText(_translate("SecondWindow", "Second Window"))
class SecondWindow(QtWidgets.QMainWindow, Ui_SecondWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
class MainWindow(QtWidgets.QMainWindow, Ui_firstWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
######To Open second window###########
self.btn_next.clicked.connect(self.secondWindow)
def secondWindow(self):
self.window = SecondWindow()
###To go back to first windo######
self.window.btn_back.clicked.connect(self.openBackFirstWindow)
self.window.show()
self.hide()
###function to go back the first window######
def openBackFirstWindow(self):
self.show()
self.window.hide()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
app.setStyle('Fusion')
firstWindow = MainWindow()
firstWindow.show()
sys.exit(app.exec_())

Related

Print from QLineEdit

i have a QLineedit which i want to print out the user input once the button is pressed but it keeps throwing out this error
Process finished with exit code -1073740791 (0xC0000409)
from PyQt5.QtWidgets import QMessageBox
from PyQt5 import QtCore, QtGui, QtWidgets
import webbrowser
def subscribe_clicked():
print(sub.text())
msg = QMessageBox()
msg.setWindowTitle("Subscribe")
msg.setText("You will now recieve updates")
msg.setIcon(QMessageBox.Question)
msg.exec_()
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(723, 785)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.gridLayout_2 = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout_2.setObjectName("gridLayout_2")
self.join = QtWidgets.QLabel(self.centralwidget)
self.join.setObjectName("join")
self.gridLayout_2.addWidget(self.join, 1, 0, 1, 1)
self.sub = QtWidgets.QLineEdit(self.centralwidget)
self.sub.setObjectName("sub")
self.subscribe = QtWidgets.QPushButton(self.centralwidget)
self.subscribe.clicked.connect(subscribe_clicked)
self.subscribe.setObjectName("subscribe")
self.gridLayout_2.addWidget(self.subscribe, 3, 0, 1, 1)
self.sub.raise_()
self.subscribe.raise_()
self.sub.raise_()
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 723, 26))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
if i put in a manual entry it prints fine , but it wont call the information from the QlineEdit text box
The reason for error is in function
def subscribe_clicked():
print(sub.text())
msg = QMessageBox()
msg.setWindowTitle("Subscribe")
msg.setText("You will now recieve updates")
msg.setIcon(QMessageBox.Question)
msg.exec_()
In line print(sub.text()) the sub is undefined since it doesn't exist out of Ui_MainWindow. Therefore it throws an error:
Process finished with exit code -1073740791 (0xC0000409)
We can fix the problem by passing sub which is a QLineEdit in MainWindow class to subscribe_clicked() function. By doing the following:
Pass parameter to function with lambda by changing:
self.subscribe.clicked.connect(subscribe_clicked)
To
self.subscribe.clicked.connect(lambda:subscribe_clicked(self.sub))
Add parameter to function
def subscribe_clicked(sub):
print(sub.text())
msg = QMessageBox()
msg.setWindowTitle("Subscribe")
msg.setText("You will now recieve updates")
msg.setIcon(QMessageBox.Question)
msg.exec_()
Full Code:
from PyQt5.QtWidgets import QMessageBox
from PyQt5 import QtCore, QtGui, QtWidgets
import webbrowser
def subscribe_clicked(sub):
print(sub.text())
msg = QMessageBox()
msg.setWindowTitle("Subscribe")
msg.setText("You will now recieve updates")
msg.setIcon(QMessageBox.Question)
msg.exec_()
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(723, 785)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.gridLayout_2 = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout_2.setObjectName("gridLayout_2")
self.join = QtWidgets.QLabel(self.centralwidget)
self.join.setObjectName("join")
self.gridLayout_2.addWidget(self.join, 1, 0, 1, 1)
self.sub = QtWidgets.QLineEdit(self.centralwidget)
self.sub.setObjectName("sub")
self.subscribe = QtWidgets.QPushButton(self.centralwidget)
self.subscribe.clicked.connect(lambda:subscribe_clicked(self.sub))
self.subscribe.setObjectName("subscribe")
self.gridLayout_2.addWidget(self.subscribe, 3, 0, 1, 1)
self.sub.raise_()
self.subscribe.raise_()
self.sub.raise_()
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 723, 26))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())

How to make Qlistwidgetitems checked automatically if same items are in the specified list?

Below is the example code:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(394, 356)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.listWidget = QtWidgets.QListWidget(self.centralwidget)
self.listWidget.setGeometry(QtCore.QRect(60, 30, 241, 192))
self.listWidget.setObjectName("listWidget")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(130, 250, 75, 23))
self.pushButton.setObjectName("pushButton")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 394, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
players = ["Player 1","Player 2","Player 3","Player 4"]
for i in players:
item = QtWidgets.QListWidgetItem(i)
item.setFlags(item.flags() | QtCore.Qt.ItemIsUserCheckable)
item.setCheckState(QtCore.Qt.Unchecked)
self.listWidget.addItem(item)
self.selected_list = ["Player 1", "Player 4"]
self.pushButton.clicked.connect(self.find_the_list)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "PushButton"))
def find_the_list(self):
print("OKAY")
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
The players = ["Player 1","Player 2","Player 3","Player 4"] list has been added in to the QListWidgetItem as UserCheckable. And the second list self.selected_list = ["Player 1", "Player 4"] is have tow items and the second list is changeable. Now I want to check the boxes of QlistWidgetitems if the second list have the matched items.
You could do something like this:
def find_the_list(self):
for i in range(self.listWidget.count()):
item = self.listWidget.item(i)
if item.text() in self.selected_list:
item.setCheckState(QtCore.Qt.Checked)
else:
item.setCheckState(QtCore.Qt.Unchecked)

Return a value from a new window in pyqt5

I wanted to open a new window by clicking on the pushbutton and type a number in the new window. After that when clicking on the "Ok" Button, the second window will be closed and the written number will be shown in the label, which was existed in the initial window. I wrote the following code but it writes 0 in the label and doesnt update.
The first Window:
from PyQt5 import QtCore, QtWidgets
from load3D import load3
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(316, 284)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(60, 60, 191, 121))
self.label.setStyleSheet("background-color: rgb(255, 255, 255);")
self.label.setText("")
self.label.setObjectName("label")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(60, 190, 75, 23))
self.pushButton.setObjectName("pushButton")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 316, 26))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
self.pushButton.clicked['bool'].connect(self.get_value)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def get_value(self):
length = self.load3load()
self.label.setText(str(length))
def load3load(self):
self.MainWindow = QtWidgets.QMainWindow()
self.x = 0
self.ui = load3(self.x)
self.ui.setupUi(self.MainWindow)
self.MainWindow.show()
return self.ui.x
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "Click"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
And The second window:
from PyQt5 import QtCore, QtGui, QtWidgets
class load3(object):
def __init__(self, x):
self.x = 0
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(283, 340)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(20, 40, 71, 31))
font = QtGui.QFont()
font.setPointSize(18)
self.label.setFont(font)
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setObjectName("label")
self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit.setGeometry(QtCore.QRect(90, 47, 113, 20))
self.lineEdit.setObjectName("lineEdit")
font = QtGui.QFont()
font.setPointSize(18)
self.buttonBox = QtWidgets.QDialogButtonBox(self.centralwidget)
self.buttonBox.setGeometry(QtCore.QRect(120, 260, 156, 23))
self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
self.buttonBox.setObjectName("buttonBox")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 283, 26))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.buttonBox.accepted.connect(self.accept)
self.buttonBox.accepted.connect(MainWindow.close)
self.buttonBox.rejected.connect(MainWindow.close)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def accept(self):
self.x = self.lineEdit.text()
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "Image properties"))
self.label.setText(_translate("MainWindow", "X:"))
Any thoughts how to make it work ?
First of all, you should never edit the files generated with pyuic. They are intended to be used only as imported module. Read more about using Designer to understand how use them properly.
Second: if you need an input from the user from another window, you should use a QDialog, not a QMainWindow.
Then, if you only need a simple input value, use QInputDialog, possibly from one of its static methods, in your case getInt() will suffice.
Finally, the reason for which your code doesn't work is that after creating and showing the window you immediately get the x value, but after that the function returns immediately, since there's nothing "blocking" it (so it won't wait for any input from the user). That's what QDialogs are for: they wait from some input from the user before returning.
If you don't have the .ui files anymore, recreate them, then generate again the python files with pyuic and leave them there.
Supposing you've created a file named ui_mainwindow.py for the main window and ui_inpudialog.py for a dialog with a spinbox (not a line edit, since you need a numeric value) and a buttonbox:
from PyQt5 import QtWidgets
from ui_mainwindow import Ui_MainWindow
from ui_inputdialog import Ui_Dialog
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.pushButton.clicked.connect(self.get_value)
def get_value(self):
dialog = InputDialog(self)
# this will show the dialog and wait for the user to accept or reject it
if dialog.exec():
# get the value from the dialog
self.label.setText(str(dialog.getValue()))
class InputDialog(QtWidgets.QDialog, Ui_Dialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setupUi(self)
def getValue(self):
# return the current value of the spinbox
return self.spinBox.value()
Alternatively, if you don't need specific customization of the input dialog, just use QInputDialog as suggested before:
from PyQt5 import QtWidgets
from ui_mainwindow import Ui_MainWindow
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.pushButton.clicked.connect(self.get_value)
def get_value(self):
length = QtWidgets.QInputDialog.getInt(self, 'Insert value', 'Value',
min=0, max=100)
self.label.setText(str(length))

Pyqt5 QFileDialog not working in my program for Getting Directories

I have This Qt MainWindow Shown Below:
I want my Browse button to Open a Dialog box for selecting Specific Directory.
I Went through the various post on Stack Overflow, I tried implementing the solution in the post, but It's not working for me.
Here is my Code :
from PyQt5 import QtCore, QtGui, QtWidgets
import os
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout.setObjectName("gridLayout")
self.gridLayout_2 = QtWidgets.QGridLayout()
self.gridLayout_2.setObjectName("gridLayout_2")
self.start_button = QtWidgets.QPushButton(self.centralwidget)
self.start_button.setAutoFillBackground(False)
self.start_button.setAutoDefault(False)
self.start_button.setDefault(False)
self.start_button.setFlat(False)
self.start_button.setObjectName("start_button")
self.start_button.clicked.connect(lambda: self.start_button_click())
self.gridLayout_2.addWidget(self.start_button, 0, 0, 1, 1)
self.Br_button = QtWidgets.QPushButton(self.centralwidget)
self.Br_button.setObjectName("Br_button")
self.Br_button.clicked.connect(lambda: self.browse_button())
self.gridLayout_2.addWidget(self.Br_button, 2, 0, 1, 1)
self.label = QtWidgets.QLabel(self.centralwidget)
font = QtGui.QFont()
font.setPointSize(14)
font.setBold(True)
font.setWeight(75)
self.label.setFont(font)
self.label.setObjectName("label")
self.gridLayout_2.addWidget(self.label, 2, 1, 1, 1, QtCore.Qt.AlignHCenter)
self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
self.tableWidget.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.setColumnCount(0)
self.tableWidget.setRowCount(0)
self.gridLayout_2.addWidget(self.tableWidget, 3, 0, 1, 2)
self.gridLayout.addLayout(self.gridLayout_2, 0, 0, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.start_button.setToolTip(_translate("MainWindow", "Start The Program"))
self.start_button.setText(_translate("MainWindow", "Start"))
self.Br_button.setToolTip(_translate("MainWindow", "Browse the File Location to Watch on"))
self.Br_button.setText(_translate("MainWindow", "Browse"))
def start_button_click(self):
self.label.setText("Hello")
def browse_button(self):
fileName = QtWidgets.QFileDialog.getExistingDirectory(QtWidgets.QFileDialog,None,"Open Directory",os.getcwd(), QtWidgets.QFileDialog.ShowDirsOnly)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
When I Click on the Browse button it closes the Application abruptly after few seconds and I am Getting This Error Shown below:
Try it:
import sys
import os
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
class Form(QMainWindow):
def __init__(self,parent=None):
super().__init__(parent)
self.plainTextEdit = QPlainTextEdit()
self.plainTextEdit.setFont(QFont('Arial', 11))
openDirButton = QPushButton("Open Directory")
openDirButton.clicked.connect(self.browse_button)
layoutV = QVBoxLayout()
layoutV.addWidget(openDirButton)
layoutH = QHBoxLayout()
layoutH.addLayout(layoutV)
layoutH.addWidget(self.plainTextEdit)
centerWidget = QWidget()
centerWidget.setLayout(layoutH)
self.setCentralWidget(centerWidget)
def browse_button(self):
fileName = QFileDialog.getExistingDirectory(
#QtWidgets.QFileDialog, # ???
None,
"Open Directory",
os.getcwd(),
QFileDialog.ShowDirsOnly)
self.plainTextEdit.appendHtml("<br>Chose a folder: <b>{}</b>".format(fileName))
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Form()
ex.resize(740,480)
ex.setWindowTitle("PyQt5-QFileDialog")
ex.show()
sys.exit(app.exec_())

Python - PyQt5 how to take file as a input?

There is screenshot attached below:So basically i want to take file as a input(i.e suffix_list.txt) instead of specifying file location inside the function and when i clicked action button i need execute a output inside QtTextEdit
I tried something but i can't get it. Please help me out. I'm new to PyQt5Thanks
This is my gui code:
# -*- coding: utf-8 -*-
# Created by: PyQt5 UI code generator 5.10
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(514, 381)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.text_output = QtWidgets.QTextEdit(self.centralwidget)
self.text_output.setGeometry(QtCore.QRect(80, 10, 351, 271))
self.text_output.setObjectName("text_output")
self.btn_Action = QtWidgets.QPushButton(self.centralwidget)
self.btn_Action.setGeometry(QtCore.QRect(220, 300, 75, 23))
self.btn_Action.setObjectName("btn_Action")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 514, 21))
self.menubar.setObjectName("menubar")
self.menuFile = QtWidgets.QMenu(self.menubar)
self.menuFile.setObjectName("menuFile")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.actionOpen_File = QtWidgets.QAction(MainWindow)
self.actionOpen_File.setObjectName("actionOpen_File")
self.menuFile.addAction(self.actionOpen_File)
self.menubar.addAction(self.menuFile.menuAction())
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.btn_Action.setText(_translate("MainWindow", "Action"))
self.menuFile.setTitle(_translate("MainWindow", "File"))
self.actionOpen_File.setText(_translate("MainWindow", "Open File"))
def file_open(self):
name, _ = QtWidgets.QFileDialog.getOpenFileName(self, 'Open File', options=QtWidgets.QFileDialog.DontUseNativeDialog)
file = open(name, 'r')
with file:
text = file.read()
self.textEdit.setText(text)
def suffix_remove(self):
suffix_list = []
dictionary = {}
lists = ['athletic','kitchenette','helpful','terrify']
with open('suffix_list.txt') as f:
for lines in f:
lines = lines.rstrip()
suffix_list.append(lines)
for words in lists:
for suffix in suffix_list:
if words.endswith(suffix):
final_list = str.replace(words,suffix,'')
dictionary[words] = final_list
return dictionary
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
ui.btn_Action.clicked.connect(lambda:
ui.text_output.append(str(ui.suffix_remove())))
MainWindow.show()
sys.exit(app.exec_())
The two main problems you have are that you do not call your file_open method and you are supplying an instance of Ui_MainWindow to your file dialog when it needs to be an instance of MainWindow. Here is how to fix this:
def retranslateUi(self, MainWindow):
self.main_window = MainWindow
# your code here
self.actionOpen_File.triggered.connect(self.file_open)
def file_open(self):
name, _ = QtWidgets.QFileDialog(self.main_window, 'Open File', options=QtWidgets.QFileDialog.DontUseNativeDialog)
# your code here
There are, however, some problems outside the scope of this question in your code structure that will make this difficult to expand upon.
Thanks everyone <
Here is my answer what i actually want to do.
# -*- coding: utf-8 -*-
# Created by: PyQt5 UI code generator 5.10
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(514, 381)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.text_output = QtWidgets.QTextEdit(self.centralwidget)
self.text_output.setGeometry(QtCore.QRect(80, 10, 351, 271))
self.text_output.setObjectName("text_output")
self.btn_Action = QtWidgets.QPushButton(self.centralwidget)
self.btn_Action.setGeometry(QtCore.QRect(220, 300, 75, 23))
self.btn_Action.setObjectName("btn_Action")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 514, 21))
self.menubar.setObjectName("menubar")
self.menuFile = QtWidgets.QMenu(self.menubar)
self.menuFile.setObjectName("menuFile")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.actionOpen_File = QtWidgets.QAction(MainWindow)
self.actionOpen_File.setObjectName("actionOpen_File")
self.actionOpen_File.setShortcut('Ctrl+O')
self.actionOpen_File.triggered.connect(self.file_open)
self.menuFile.addAction(self.actionOpen_File)
self.menubar.addAction(self.menuFile.menuAction())
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.btn_Action.setText(_translate("MainWindow", "Action"))
self.menuFile.setTitle(_translate("MainWindow", "File"))
self.actionOpen_File.setText(_translate("MainWindow", "Open File"))
def file_open(self):
name, _ = QtWidgets.QFileDialog.getOpenFileName(None, 'Open File', options=QtWidgets.QFileDialog.DontUseNativeDialog)
file = open(name, 'r')
with file:
text = file.read()
self.text_output.setText(text)
def suffix_remove(self):
suffix_list = []
dictionary = {}
lists = ['athletic','kitchenette','helpful','terrify']
f = self.text_output.toPlainText()
for lines in f:
lines = lines.rstrip()
suffix_list.append(lines)
for words in lists:
for suffix in suffix_list:
if words.endswith(suffix):
final_list = str.replace(words,suffix,'')
dictionary[words] = final_list
return dictionary
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
ui.btn_Action.clicked.connect(lambda: ui.text_output.append(str(ui.suffix_remove())))
MainWindow.show()
sys.exit(app.exec_())

Resources