I am coding a application which needs a custom buttons in QMessageBox. i managed to create an example in QT designer which is given below.
i wanted to do this in a QMessageBox.
I am using python 2.6.4 and PyQt4. please, can any one help.
Here is an example of building a custom message box from the ground up.
import sys
from PyQt4 import QtCore, QtGui
class Example(QtGui.QDialog):
def __init__(self, parent=None):
super(Example, self).__init__(parent)
msgBox = QtGui.QMessageBox()
msgBox.setText('What to do?')
msgBox.addButton(QtGui.QPushButton('Accept'), QtGui.QMessageBox.YesRole)
msgBox.addButton(QtGui.QPushButton('Reject'), QtGui.QMessageBox.NoRole)
msgBox.addButton(QtGui.QPushButton('Cancel'), QtGui.QMessageBox.RejectRole)
ret = msgBox.exec_()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())
manuel-gutierrez, why do you inherit from QDilaog? You can inherit from QMessageBox. It's much simpler and less code
import sys
from PyQt4.QtGui import QMessageBox, QPushButton, QApplication
from PyQt4.QtCore import Qt
class ErrorWindow(QMessageBox):
def __init__(self, parent=None):
QMessageBox.__init__(self, parent)
self.setWindowTitle("Example")
self.addButton(QPushButton("Yes"), QMessageBox.YesRole )
self.addButton(QPushButton("No"), QMessageBox.NoRole)
self.addButton(QPushButton("Cancel"), QMessageBox.RejectRole)
if __name__ == "__main__":
app = QApplication(sys.argv)
ex = ErrorWindow()
ex.setText("some error")
ex.show()
sys.exit(app.exec_())
The standard QMessageBox "impose an interpretation of the response", being accepted, rejected or canceled.
Here is a version that allows arbitrary buttons, as much as wanted, and leave the interpreatation up to the user.
And it simplifies the sourcecode a bit.
The argument "buttons" gives a text list, this makes the buttons.
The return value is the text of the clicked botton.
So the user can do what he want's with that.
Note: This might be against UI-Standards and therefore less robust, but hey.
Note2: Since it's 2021, i use PyQt5 and python 3.7
I just posted this in case someone prefer this more generic approach.
#!/usr/bin/python3
# -*- coding: utf-8 -*-
""" A more generic, a bit simplified message box also known as 'popup' """
from PyQt5 import QtWidgets as QW
class Popup(QW.QMessageBox):
def __init__(
self,
title,
text,
buttons = ["Ok"]
):
super(Popup, self).__init__()
self.setWindowTitle(title)
self.setText(text)
self.buttons = buttons
for txt in self.buttons:
b = QW.QPushButton(txt)
self.addButton(b, QW.QMessageBox.NoRole)
def do(self):
answer = self.exec_()
text = self.buttons[answer]
return text
if __name__ == "__main__": # test
class Tester(QW.QWidget):
def __init__(self):
super(Tester, self).__init__()
btn = QW.QPushButton("do it")
btn.clicked.connect(self.klick)
layout = QW.QHBoxLayout(self)
layout.addWidget(btn)
def klick(self, text):
r = Popup(
"choose a letter",
"What is your favorite\nLetter\namong a to e ?",
buttons = "a,b,c,d,e".split(","))
print("result = ",r.do())
import sys
app = QW.QApplication(sys.argv)
widget = Tester()
widget.setGeometry(400,400,100,100)
widget.show()
sys.exit(app.exec_())
Related
import sys
from PySide2.QtCore import QFile
from PySide2.QtWidgets import QApplication, QMainWindow
from PySide2.QtUiTools import QUiLoader
class MyMainWindow(QMainWindow):
def __init__(self):
super().__init__()
loader = QUiLoader()
self.ui = loader.load("mainWindow.ui", self)
self.ui.pushButton_call_dialog.clicked.connect(self.call_dialog)
self.ui.close()
self.ui.show()
def call_dialog(self):
loader = QUiLoader()
self.dialog = loader.load("dialog.ui")
self.dialog.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MyMainWindow()
window.show
sys.exit(app.exec_())
Hi everyone,
any idea why the second (dialog) window closes the entire application?
Of course, it is not a crash since i'm getting a message saying:
Process finished with exit code 0
Thanks for your help
You could handle your QDialog on a separate class, and then make them interact only, the structure might change a bit, but you can see if it's a viable answer:
import sys
from PySide2.QtWidgets import *
class MyWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
button = QPushButton("Dialog")
button.clicked.connect(self.open_dialog)
self.setCentralWidget(button)
def open_dialog(self):
dialog = MyDialog()
dialog.show()
dialog.exec_()
class MyDialog(QDialog):
def __init__(self):
QDialog.__init__(self)
button = QPushButton("Close")
button.clicked.connect(self.close_dialog)
layout = QHBoxLayout()
layout.addWidget(button)
self.setLayout(layout)
def close_dialog(self):
self.close()
if __name__ == "__main__":
app = QApplication()
m = MyWindow()
m.show()
sys.exit(app.exec_())
Just notice that you should include the setUp step on each class.
Hope it helps.
To put the dialog into a separate class didn't work for either.
Every time the Dialog.close() event was called, it closes the whole application.
What worked for me, was to use hide() instead
I'm a beginner in python , and I try to generate the frame with pyQt.
Here is my code , and I have some trouble that can not show a correct frame .
At first I wrote , and it can showed the result that I want.
#!/usr/bin/python
import sys
from PyQt4 import QtGui
app = QtGui.QApplication(sys.argv)
widget = QtGui.QWidget()
widget.resize(250, 150)
widget.setWindowTitle('simple2')
widget.show()
sys.exit(app.exec_())
I changed the wording of object-oriented later , and it can't show a frame which I except.
#!/usr/bin/python
import sys
from PyQt4 import QtGui
class Apple(QtGui.QWidget):
def _int_(self,parent=None):
super().__init__()
self.widget = QtGui.QWidget()
self.resize(250, 150)
self.setWindowTitle('simple2')
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
mywidget = Apple()
mywidget.show()
sys.exit(app.exec_())
Someone knows how do I fix my error ?
You have made a typo in your code
def _int_(self,parent=None):
should be
def __init__(self, parent=None):
Edit your code this way:
#!/usr/bin/python
# -* coding: utf-8 -*-
import sys
from PyQt4 import QtGui
class Apple(QtGui.QMainWindow):
def _init_(self): # if you have no parent you don't need to write parent = None. And yes, there was a typo
super(Apple, self).__init__() # it's a little bit better than super().__init__()
#self.widget = QtGui.QWidget() # you've already init QWidget. This code do nothing
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
mywidget = Apple()
mywidget.setWindowTitle('simple2') # here must be window title
mywidget.resize(250, 150) # and resizing
mywidget.show()
sys.exit(app.exec_())
Now you get what you want
In PyQt4 I have a main window which when the settings button is clicked opens the settings dialog
from PyQt4 import QtCore, QtGui
import ui_Design, ui_Settings_Design
class MainDialog(QtGui.QMainWindow, ui_Design.Ui_arbCrunchUI):
def __init__(self, parent=None):
super(MainDialog, self).__init__(parent)
self.setupUi(self)
self.settingsBtn.clicked.connect(lambda: self.showSettings())
def showSettings(self):
dialog = QtGui.QDialog()
dialog.ui = SettingsDialog()
dialog.ui.setupUi(dialog)
dialog.exec_()
The above works and my SettingsDialog is displayed but I cant get the setPageIndex to work
class SettingsDialog(QtGui.QDialog, ui_Settings_Design.Ui_SettingsDialog):
def __init__(self, parent=None):
super(SettingsDialog, self).__init__(parent)
self.setupUi(self)
self.bookSettingsBtn.clicked.connect(self.setPageIndex)
#QtCore.pyqtSlot()
def setPageIndex(self):
print 'selected'
self.settingsStackedWidget.setCurrentIndex(0)
The bookSettingsBtn is a QToolButton
self.bookSettingsBtn = QtGui.QToolButton(self.navigationFrame)
And the settingsStackedWidget is a QStackedWidget
self.settingsStackedWidget = QtGui.QStackedWidget(SettingsDialog)
At this point I am pretty confused on signals and slots and nothing I have read clears this up - if anyone can point out what I am doing wrong above and also potentially direct me to a good (beginners) guide / tutorial on signals and slots it would be greatly appreciated
I would also like to know how to make setPageIndex work as follows:
def setPageIndex(self, selection):
self.settingsStackedWidget.setCurrentIndex(selection)
I'm not sure why you're doing the following, but that's the issue:
def showSettings(self):
dialog = QtGui.QDialog()
dialog.ui = SettingsDialog()
dialog.ui.setupUi(dialog)
dialog.exec_()
SettingsDialog itself is a proper QDialog. You don't need to instantiate another QDialog.
Right now, you're creating an empty QDialog and then populate it with the same ui as SettingsDialog (i.e. setupUi(dialog)), then you show this dialog. But... The signal connection is for SettingsDialog, and the dialog you're showing doesn't have that.
Basically, you don't need that extra QDialog at all. The following should be enough:
def showSettings(self):
dialog = SettingsDialog()
dialog.exec_()
Ok. So here is an example how you pass an argument to a slot
from functools import partial
# here you have a button bookSettingsBtn:
self.bookSettingsBtn = QtGui.QPushButton("settings")
self.bookSettingsBtn.clicked.connect(partial(self.setPageIndex, self.bookSettingsBtn.text()))
#pyqtSlot(str) # this means the function expects 1 string parameter (str, str) 2 string parameters etc.
def setPageIndex(self, selection):
print "you pressed button " + selection
In your case the argument would be an int. Of course you have to get the value from somewhere
and then put it in the partial part as the argument (here I just used the text of the button),
but you can use int, bool etc. Just watch the slot signature.
Here is a tutorial that helped me:
http://zetcode.com/gui/pyqt4/
I hope this helps.
Hey here I have a fully running example (just copy paste it in a python file and run it):
Maybe this helps you. It's a small example but here you see how it works.
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from functools import partial
class MyForm(QMainWindow):
def __init__(self, parent=None):
super(MyForm, self).__init__(parent)
button1 = QPushButton('Button 1')
button2 = QPushButton('Button 2')
button1.clicked.connect(partial(self.on_button, button1.text()))
button2.clicked.connect(partial(self.on_button, button1.text()))
layout = QHBoxLayout()
layout.addWidget(button1)
layout.addWidget(button2)
main_frame = QWidget()
main_frame.setLayout(layout)
self.setCentralWidget(main_frame)
#pyqtSlot(str)
def on_button(self, n):
print "Text of button is: " + str(n)
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
form = MyForm()
form.show()
app.exec_()
So I dont really understand why but changing the way the settingsDialog is called from the MainWindow has fixed my problem. I guess the parent window needed to be specified??:
class MainDialog(QtGui.QMainWindow, ui_Design.Ui_arbCrunchUI):
....
def showSettings(self):
self.settingsDialog = QtGui.QDialog(self)
self.settingsDialog.ui = SettingsDialog(self)
self.settingsDialog.ui.show()
class SettingsDialog(QtGui.QDialog, ui_Settings_Design.Ui_SettingsDialog):
def __init__(self, parent=None):
super(SettingsDialog, self).__init__(parent)
self.setupUi(self)
self.bookSettingsBtn.clicked.connect(partial(self.setPageIndex, 1))
#QtCore.pyqtSlot(int)
def setPageIndex(self, selection):
self.settingsStackedWidget.setCurrentIndex(selection)
I'd like to make a panel-like application using PyQt4 for Linux. for this i need the window i created:
to be undecorated
to have reserved space
to appear on all workspaces
From reading the documentation i've got the idea that i should use QtWindowFlags. But i have no clue as to how to do that. Also i believe there should be a Qt.WindowType hint somewhere telling the WM the window's a "dock" application. I have made this with pygtk following this thread, but here with Qt i don't really know how to handle this. (I need Qt for its ability to theme/skin application more easily.)
Below is the current code i made (nothing extraordinary).
import sys
from PyQt4 import QtGui
class Panel(QtGui.QWidget):
def __init__(self, parent=None): ## should the QtWindowFlag be here?
QtGui.QWidget.__init__(self, parent) ## should the QtWindowFlag be there as well?
self.setWindowTitle('QtPanel')
self.resize(QtGui.QDesktopWidget().screenGeometry().width(), 25)
self.move(0,0)
def main():
app = QtGui.QApplication(sys.argv)
panel = Panel()
panel.show()
sys.exit(app.exec_())
return 0
if __name__ == '__main__':
main()
Can anyone help me with this? Thanks :)
Read about the QWidget.windowFlags property: http://doc.qt.nokia.com/4.7/qwidget.html#windowFlags-prop
Example:
>>> from PyQt4 import QtGui, QtCore
>>> app = QtGui.QApplication([])
>>> win = QtGui.QMainWindow()
>>> win.setWindowFlags(win.windowFlags() | QtCore.Qt.FramelessWindowHint)
>>> win.show()
import sys
from PyQt4 import QtGui, QtCore
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
qbtn = QtGui.QPushButton('Quit', self)
#qbtn.clicked.connect(QtCore.QCoreApplication.instance().quit)
qbtn.clicked.connect(self.test)
qbtn.resize(qbtn.sizeHint())
qbtn.move(50, 50)
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('Quit button')
self.setWindowFlags(self.windowFlags() | QtCore.Qt.FramelessWindowHint)
self.show()
def test(self):
print "test"
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
The solution is to use Python-Xlib, and it has been described in an answer on a universal way to reserve screen space on X.
Please can someone tell me what im doing wrong here with respect to calling pwTxt.text.
#!/usr/bin/python
import sys
from PyQt4 import QtCore, QtGui
from mainwindow import Ui_MainWindow
class MyForm(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
def on_pwExtract_pressed(self):
print self.pwTxt.text
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = MyForm()
myapp.show()
sys.exit(app.exec_())
The line print self.pwTxt.text fails because it can't find the widget, pwTxt is a QLineEdit defined on the main window. I just made it in QTDesigner and generated python code with pyuic4.
How do I correctly reference other widgets on the same window, in this case I just want to get the text from a QLineEdit named pwTxt when the QPushButton pwExtract is pressed.
Thanks a lot.
Try:
print self.ui.pwTxt.text()