PyQt5 Quit button - python

Could you please explain why the quit push button does not work properly in this case:
import sys
from PyQt5.QtWidgets import QWidget, QPushButton, QApplication
from PyQt5.QtCore import QCoreApplication
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
qbtn = QPushButton('Quit', self)
qbtn.clicked.connect(QCoreApplication.instance().quit)
qbtn.move(50, 50)
self.setGeometry(300, 300, 250, 150)
self.show()
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
But works if I include the last three lines in a function:
def fun():
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
fun()
I don't understand the mechanics :(

I ran into the same problem while using linux. This code comes from a tutorial
on zetcode.com for PyQt5 in the quitButton.py file. Here is the solution that I found works:
Instead of using:
qbtn.clicked.connect(QCoreApplication.instance().quit)
Replace it with this:
qbtn.clicked.connect(self.close)
After this, you shouldn't need to call it in a separate function. Hope this helps!

I tried this recently. I need a sure exit from within spyder and this always seems a problem with pyqt. I found
qbtn.clicked.connect(QCoreApplication.instance().quit) will quit and leave window open.
qbtn.clicked.connect(self.close) will close the window but leave the process running.
qbtn.clicked.connect(QCoreApplication.instance().quit) and
qbtn.clicked.connect(self.close) sequentially will quit and close window.
This is pyqt5 on Python 3.8.8. Hope this is helpful.

Related

Getting blank form when running PyQt application

I wrote the calculator code, made the design in QT designer, converted the design file from ui format to py. When the program starts, a white window pops up, just without everything. Maybe someone knows what the problem is, I will be very grateful if someone helps)
import sys
from PySide6.QtWidgets import QApplication, QMainWindow
from design import Ui_MainWindow
class Calculator(QMainWindow):
def __init__(self):
super(Calculator, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
if __name__== "__main__":
app = QApplication(sys.argv)
window = Calculator()
window.show()
sys.exit(app.exec())

how to close a window in pyqt5 and terminate the program? program gets stuck

I want to create a window in pyqt5 and then close it. For some reason the program does not exit after closing the window. It gets stuck. I have been reading several related posts but none give a clear answer.
I have already tried code such as "self.object.close()", "app.quit()", even "self.object.destroy()", but all work in the same way. The only thing that really closes the window is by clicking the x (close) at the window itself. But this is not the behavior I need. I would like to close the window using my code.
import sys
from PyQt5 import QtWidgets
from PyQt5 import QtCore
from PyQt5 import QtGui
from PyQt5.QtCore import pyqtSlot, pyqtSignal
class window(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(300, 300, 480, 300)
self.setWindowTitle('Hello World')
self.setWindowLayout()
def setWindowLayout(self):
self.w = QtWidgets.QWidget(self)
self.layout = QtWidgets.QHBoxLayout()
self.label = QtWidgets.QLabel('Hello World Label')
self.layout.addWidget(self.label)
self.w.setLayout(self.layout)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
main_window = window()
main_window.show()
main_window.close()
sys.exit(app.exec_())
Once I close the window using
main_window.close(). I want my program to exit.
I apologize if this was resolved in a different post. I searched the answer and none solves my problem.
Thanks.
It seems to me that it is a bug since according to the docs the application should be closed if there is no top-level window but it seems that it is not verified if the closing of the window is not after the event-loop starts. A workaround is to use QTimer.singleShot(0, ...) to close the window:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class window(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(300, 300, 480, 300)
self.setWindowTitle('Hello World')
self.setWindowLayout()
def setWindowLayout(self):
self.w = QtWidgets.QWidget(self)
self.layout = QtWidgets.QHBoxLayout()
self.label = QtWidgets.QLabel('Hello World Label')
self.layout.addWidget(self.label)
self.w.setLayout(self.layout)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
main_window = window()
main_window.show()
QtCore.QTimer.singleShot(0, main_window.close) # <---
sys.exit(app.exec_())

Window icon does not show

I study this tutorial http://zetcode.com/gui/pyqt5/firstprograms/
and code here.
import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QIcon
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(300, 300, 300, 220)
self.setWindowTitle('Icon')
self.setWindowIcon(QIcon('web.png'))
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
Can I show Window icon? I use PyQt5, Python3.4 and Linuxmint 17.2 cinnamon.
i am not sure, what you expected:
the windowicon is shown as applicationIcon (e.g. here on ubuntu gnome, see my code in the background)
If no icon has been set, windowIcon() returns the application icon
(QApplication::windowIcon()).
http://doc.qt.io/qt-5/qwidget.html#windowIcon-prop
looks on ubuntu like this:
so i think, the code is working correctly
Check where the icon file is placed. It should be placed in the execution directory in your case. You can check the execution directroy with the following change:
if __name__ == '__main__':
import os
print("Work dir:" + os.getcwd())
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
try PySide.QtGui.QApplication.setWindowIcon(icon). Like this:
if __name__ == '__main__':
app = QApplication(sys.argv)
app.setWindowIcon(QIcon('web.png'))
ex = Example()
sys.exit(app.exec_())
I faced the exact same problem.
First things first. There is no setWindowIcon() method under QWidget or QMainWindow classes, in fact. you should be trying to set the QIcon at the Application level as follows.
app = QApplication(sys.argv)
app.setWindowIcon(QtGui.QIcon('home.png'))
Second, the icon thus created using this code does not reflect on the title of the window, instead it will reflect as an application icon as shown in the image below. the home.png
Application icon in Mac not the Window Icon
Finally, the path does not really matter, it can be an absolute path or a relative path, the system will consider either.

My python script turn off touchpad and power button why?

I use KDE on Manjaro linux. I have this script in python to turn off touchpad:
#!/usr/bin/python
import sys
from PyQt5.QtWidgets import QWidget, QPushButton, QApplication
from PyQt5.QtCore import QCoreApplication
from subprocess import call
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
qbtn = QPushButton('On', self)
qbtn.clicked.connect(self.handleButtonOn)
qbtn.resize(qbtn.sizeHint())
qbtn.move(25, 50)
qbtn = QPushButton('Off', self)
qbtn.clicked.connect(self.handleButtonOff)
qbtn.resize(qbtn.sizeHint())
qbtn.move(125, 50)
self.setGeometry(300, 300, 250, 100)
self.setWindowTitle('Touchpad On/Off')
self.show()
def handleButtonOn(self, event):
print ('On')
call(["synclient", "touchpadoff=0"])
call(["notify-send", "Your touchpad is set to ON"])
self.destroy()
def handleButtonOff(self, event):
print ('Off')
call(["synclient", "touchpadoff=1"])
call(["notify-send", "Your touchpad is set to OFF"])
self.destroy()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
It's works almost perfect (turn off my touchpad) but when I start script it's turn off my power button so I can't turn off computer by this button.
There is a problem with Yakuake too, can't write in this terminal. Finally i've start some other terminal for example "konsole" and turn off computer by shutdown command.
I'm new in python. How to make this work OK. I need turn off my touchpad, I use external mouse.
I can't reproduce your issue with power button, but I found out that self.destroy() is causing your script to freeze in some corrupted-not-responding-to-SIGINT state. Replacing self.destroy() with self.close() makes it work on my machine.
Please try replacing self.destroy() with self.close().

How to make a window that occupies the full screen without maximising?

I'm writing in python using Qt
I want to create the application window (with decorations) to occupy the full screen size. Currently this is the code I have:
avGeom = QtGui.QDesktopWidget().availableGeometry()
self.setGeometry(avGeom)
the problem is that it ignores window decorations so the frame is larger... I googled and what not, found this:
http://harmattan-dev.nokia.com/docs/library/html/qt4/application-windows.html#window-geometry
which seems to indicate I need to set the frameGeometry to the avGeom however I haven't found a way to do that. Also, in the comments in the above link it says what I'm after may not be even possible as the programme can't set the frameGeometry before running... If that is the case I just want confirmation that my problem is not solvable.
EDIT:
So I played around with the code a bit and this gives what I want... however the number 24 is basically through trial and error until the window title is visible.... I want some better way to do this... which is window manager independent..
avGeom = QtGui.QDesktopWidget().availableGeometry()
avGeom.setTop(24)
self.setGeometry(avGeom)
Now I can do what I want but purely out of trial and error
Running Ubuntu, using Spyder as an IDE
thanks
Use QtGui.QApplication().desktop().availableGeometry() for the size of the window:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from PyQt4 import QtGui, QtCore
class MyWindow(QtGui.QWidget):
def __init__(self, parent=None):
super(MyWindow, self).__init__(parent)
self.pushButtonClose = QtGui.QPushButton(self)
self.pushButtonClose.setText("Close")
self.pushButtonClose.clicked.connect(self.on_pushButtonClose_clicked)
self.layoutVertical = QtGui.QVBoxLayout(self)
self.layoutVertical.addWidget(self.pushButtonClose)
titleBarHeight = self.style().pixelMetric(
QtGui.QStyle.PM_TitleBarHeight,
QtGui.QStyleOptionTitleBar(),
self
)
geometry = app.desktop().availableGeometry()
geometry.setHeight(geometry.height() - (titleBarHeight*2))
self.setGeometry(geometry)
#QtCore.pyqtSlot()
def on_pushButtonClose_clicked(self):
QtGui.QApplication.instance().quit()
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
app.setApplicationName('MyWindow')
main = MyWindow()
main.show()
sys.exit(app.exec_())
I've always found inheritting from the QMainWindow class to be particularly useful. Like this:
import sys
from PySide.QtGui import *
from PySide.QtCore import *
class Some_APP(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
### this line here is what you'd be looking for
self.setWindowState(Qt.WindowMaximized)
###
self.show()
def main():
app = QApplication(sys.argv)
some_app = Some_APP()
sys.exit(app.exec_())
if __name__ == "__main__":
main()

Categories