PyQt5 : How to make a button close the gui after clicking - python

Here is my code for the click button:
run_btn=QtWidgets.QPushButton("Run")
def main():
print ('Starting Program')
run_btn.clicked.connect(main)
But after I click "Run", it just prints "Starting Program" again and again, and the GUI window doesn't disappear:
How can I make the button print it once and go on with the program ?
I am using PyQt5 and Python 3.4.0

Suppose that the QPushButton is inside the main widget (in the example QWidget), to close the window we use the close()
from PyQt5 import QtWidgets
import sys
app = QtWidgets.QApplication(sys.argv)
w = QtWidgets.QWidget()
line1_edit = QtWidgets.QLineEdit()
line2_edit = QtWidgets.QLineEdit()
run_btn=QtWidgets.QPushButton("Run")
def main():
print ('Starting Program')
w.close()
run_btn.clicked.connect(main)
layout = QtWidgets.QVBoxLayout()
layout.addWidget(line1_edit)
layout.addWidget(line2_edit)
layout.addWidget(run_btn)
w.setLayout(layout)
w.show()
sys.exit(app.exec_())

Related

Python Shell restart after while loop with PyQt5

actually I try to do a displayer of html page. I have some of list of html that I need to display, each page must stay visible while x secondes.
But, after the first page is display, the application crash and the python shell restart in consequence.
On my mind, I would create the window to display the page and close the application because after I will try to display png/jpg, so I need to close app to use Pygame for pictures and re-build the app to display html page after.
My list looking for it :
html page/html page/picture/html page/picture/picture
So I have build a sample code to test in while boucle the displayer :
from PyQt5 import QtWidgets, QtWebEngineWidgets, QtCore
import sys
continuer = True
while continuer:
print("Application created")
# Create application
app = QtWidgets.QApplication(sys.argv)
# Add window
win = QtWidgets.QWidget()
win.setWindowTitle('My first rendering')
# Add layout
layout = QtWidgets.QVBoxLayout()
win.setLayout(layout)
# Create QWebView
view = QtWebEngineWidgets.QWebEngineView()
view.setUrl(QtCore.QUrl('https://google.com'))
# Add QWebView to the layout
layout.addWidget(view)
# Show window, run app
win.show()
QtCore.QTimer.singleShot(7*1000, win.close)
QtCore.QTimer.singleShot(7*1000, app.quit)
print("View displayed")
# While loop
app.exec_()
print('Close Application')
print("End While Loop")
Result after executing
It's probably sys.argv in app var the mistake, but I'm new in Python so I don't know how to fix the problem.
The problem is that QApplication is not necessarily eliminated and therefore you would be creating more than one QApplication what Qt forbids, a better solution is to rethink it verifying that if it does not exist then create a new one:
import sys
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets
continuer = True
while continuer:
print("Application created")
# Create application
app = QtWidgets.QApplication.instance()
if app is None:
app = QtWidgets.QApplication(sys.argv)
# Add window
win = QtWidgets.QWidget()
win.setWindowTitle("My first rendering")
# Create QWebEngineView
view = QtWebEngineWidgets.QWebEngineView()
view.setUrl(QtCore.QUrl("https://google.com"))
# Add layout
layout = QtWidgets.QVBoxLayout(win)
win.setLayout(layout)
# Add QWebView to the layout
layout.addWidget(view)
# Show window, run app
win.show()
QtCore.QTimer.singleShot(7 * 1000, win.close)
QtCore.QTimer.singleShot(7 * 1000, app.quit)
print("View displayed")
# While loop
app.exec_()
print("Close Application")
print("End While Loop")

PyQt Creates Seperate Window For Button

Hi recently I started experimenting with the PyQt5 GUI library since Tkinter doesn't look very modern or nice. I am trying to create a very simple window with a button on it, but for some reason it opens a new window for the button. How can I solve this? Here is the code:
from PyQt5 import QtWidgets
app = QtWidgets.QApplication([])
window = QtWidgets.QWidget()
window.setGeometry(0, 0, 500, 300)
window.setWindowTitle("UI")
window.show()
btn = QtWidgets.QPushButton("Test")
btn.resize(100,100)
btn.move(100,100)
btn.show()
(app.exec_())
I am aware that I should be using classes for the GUI, but I'd like to learn the basics before I start doing that.
For a widget like the QPushButton to be part of a window, the widget must be fulfilled:
be child of the window or
be a child of some child from the window or
it is part of a layout that belongs to the window.
In your case QPushButton does not meet any of it so it will be a new window.So it can be solved using the 1 or 3 rule:
import sys
from PyQt5 import QtWidgets
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = QtWidgets.QWidget()
window.setGeometry(0, 0, 500, 300)
window.setWindowTitle("UI")
btn = QtWidgets.QPushButton("Test", window)
btn.resize(100,100)
btn.move(100,100)
window.show()
sys.exit(app.exec_())
Or:
import sys
from PyQt5 import QtWidgets
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = QtWidgets.QWidget()
window.setGeometry(0, 0, 500, 300)
window.setWindowTitle("UI")
btn = QtWidgets.QPushButton("Test")
lay = QtWidgets.QHBoxLayout(window)
lay.addWidget(btn)
window.show()
sys.exit(app.exec_())

Use pyqt4 to create GUI that runs python script

I have written a python script that manipulates data and then saves it into an excel file with the following function:
def saveData():
table = pd.DataFrame(data)
writer = pd.ExcelWriter('manipulatedData.xlsx')
table.to_excel(writer, 'sheet 1')
writer.save()
I also have the following super basic/minimalistic gui window:
from PyQt4 import QtGui
app = QtGui.QApplication(sys.argv)
window = QtGui.QWidget()
window.setGeometry(500,500,500,500)
window.setWindowTitle("PyQt Test!")
window.setWindowIcon(QtGui.QIcon('pythonLogoSmall.png'))
window.show()
sys.exit(app.exec_())
What I really would like to know is this:
1) How can I let the user of my gui select the location + name for the manipulatedData file?
2) How can I add a "run" button, that starts my python script and manipulates the data, before it saves the manipulated data to the desired location.
PyQt4 has QLineEdit() and QPushButton()
from PyQt4 import QtGui
import sys
# --- functions ---
def my_function(event=None):
print 'Button clicked: event:', event
print linetext.text()
# run your code
# --- main ---
app = QtGui.QApplication(sys.argv)
window = QtGui.QWidget()
# add "layout manager"
vbox = QtGui.QVBoxLayout()
window.setLayout(vbox)
# add place for text
linetext = QtGui.QLineEdit(window)
vbox.addWidget(linetext)
# add button
button = QtGui.QPushButton("Run", window)
vbox.addWidget(button)
# add function to button
button.clicked.connect(my_function)
window.show()
sys.exit(app.exec_())

Open window application in current window

I want to open a game application replacing the menu window.
So I have a game application which I can start with:
subprocess.call(["mygameprogram", "argument one"])
This opens up another window, but I want to replace the qt window with the game window without closing the menu window.
This is my MainWindow class:
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initMenu()
self.show()
def initMenu(self):
# load ui file
uic.loadUi("somefile.ui", self)
# add pushbutton
btn = QPushButton()
# add click listener
btn.clicked.connect(self.startLevel)
# add button to layout
self.layout_buttons.addWidget(btn)
def startLevel(self):
# open game, put the right code in here :D
pass
if __name__ == "__main__":
app = QApplication(sys.argv)
ex = MainWindow()
sys.exit(app.exec_())
Is there any solution for that? And if not, what should I do instead?
Thanks in advance

Quiting the print dialog-pyqt

I defined a print function using QPrinter and QDialog. However, when I launch the printer dialog and then press cancel, the entire mainwindow goes into not responding mode. I have tried to do QtGui.QPrintDialog.close() but does not work.
Code:
import sys
from PyQt4 import QtCore
from PyQt4 import QtGui
class QButton(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.button = QtGui.QPushButton('Button', self)
self.name='me'
self.button.clicked.connect(self.calluser)
def calluser(self):
Appli=QtGui.QApplication(sys.argv)
printer= QtGui.QPrinter()
doc=QtGui.QTextDocument("Set local variables in this printing slot." )
dialog = QtGui.QPrintDialog(printer)
dialog.setModal(True)
dialog.setWindowTitle("Print Document" )
if dialog.exec_() == True:
doc.print_(printer)
# dialog.addEnabledOption(QAbstractPrintDialog.PrintSelection)
def demo_QButton():
app = QtGui.QApplication(sys.argv)
tb = QButton()
tb.show()
app.exec_()
if __name__=='__main__':
demo_QButton()
You created a new application in the calluser method. Delete or comment the line:
Appli=QtGui.QApplication(sys.argv)
and try again. I think this time your main window will remain responsive.

Categories