I'm working on a plugin for Avogadro (chemistry software) that uses pyqt.
I've some problem with connecting a method to the clicked signal of a button.
I've my class:
class Controller(object):
def __init__(self):
self.ui = MyDialog() # self.ui.run is a QPushButton
self.ui.run.clicked.connect(self.on_run_click)
def on_run_click(self):
1/0
class MyDialog(QDialog,Ui_Dialog): # ui designer compiled
def __init__(self):
QDialog.__init__(self)
self.setupUi(self)
Why when I click the button the on_run_click isn't called?
Unless they've considerably changed something recently, this doesn't seem like the way to connect signals in PyQt. I'm more used to:
self.connect(self.ui.run, QtCore.SIGNAL("clicked()"),
self, QtCore.SLOT("on_run_click()"))
The problem is that Avogadro python wrappers don't support the new signal syntax as described in Tim's blog post:
http://timvdm.blogspot.com/2008/12/avogadro-gets-new-python-wrappers.html
Related
I am building a graphical interface for an application using PySide2. My main window is a QMainWindow and I am trying to open a pop-up window, which is a QDialog, whenever a specific action is performed on the main window.
The pop-up opens perfectly fine. However, after it is open, the main window is no longer responsive. I believe the problem is that my application is overwriting the main window with the popup window.
The error message whenever I try to change the main window's stackedWidget index is:
AttributeError: 'Ui_popupHideSuccess' object has no attribute 'stackedWidget'
The code I am using to open the main window is the following:
if __name__ == '__main__':
app = QApplication(sys.argv)
myWindow = MainWindow()
myWindow.show()
sys.exit(app.exec_())
And the code I am using to open the pop-up window is the following:
def showPopupSuccessHide(self):
self.window = QDialog()
self.ui = Ui_popupHideSuccess()
self.ui.setupUi(self.window)
self.window.show()
The code for the windows themselves are on other files (as I am using QtDesigner for developing them). I believe it to be unnecessary for resolving this issue, but I can provide it if needed. What am I doing wrong here? I need to open pop-ups and still interact with the main window after.
I have no idea how to actually resolve this. I believe my error to be in the code I am using to open the pop-up window, but I'm not sure how to tweak it for it to work properly.
TL;DR
Do not overwrite self.ui.
Explanation
How uic composition works
One of the common ways of properly using pyuic generated files is to use composition (as opposed to multiple inheritance):
from PyQt5.QtWidgets import QApplication, QMainWindow, QDialog
from ui_mainWindow import Ui_MainWindow
class MyWindow(QMainWindow):
def __init__(self):
super().__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.myLineEdit.setText('some text')
This is perfectly fine, and makes sense: the concept is that an instance of the pyuic class (sometimes called "form class") is created and then the actual window is "set up" using that instance, with the self.ui object containing references to all widgets.
Note that making the ui persistent (using an instance attribute) is actually not a strict requirement, but it is usually necessary in order to be able to directly access the widgets, which is normally important to create signal connections or read properties.
But, if that's not required, it will work anyway: the widgets are automatically "reparented" to the main window (or their direct parents), and the garbage collection is not an issue as Qt will keep its own references internally (in Qt terms, "the window takes ownership").
Technically speaking, this is completely valid:
class MyWindow(QMainWindow):
def __init__(self):
super().__init__()
Ui_MainWindow().setupUi(self)
Then, we can still access the widgets using findChild and their object names (those set in Designer):
self.findChild(QLineEdit, 'myLineEdit').setText('some text')
Obviously, it is not very practical.
Creating "child" windows
When there is the need to create a child window (usually, a dialog), it's normally suggested to use an instance attribute to avoid garbage collection:
def createWindow(self):
self.window = QDialog()
self.window.show()
If that dialog also has a Designer file, we need to do something similar to what done at the beginning. Unfortunately, a very common mistake is to create the ui instance by using the same name:
def createWindow(self):
self.window = QDialog()
self.ui = Ui_Dialog()
self.ui.setupUi(self.window)
self.ui.anotherLineEdit.setText('another text')
self.window.show()
This is theoretically fine: all works as expected. But there's a huge problem: the above overwrites self.ui, meaning that we lose all references to the widgets of the main window.
Suppose that you want to set the text of the line edit in the dialog based on the text written in that of the main window; the following will probably crash:
def createWindow(self):
self.window = QDialog()
self.ui = Ui_Dialog()
self.ui.setupUi(self.window)
self.ui.anotherLineEdit.setText(self.ui.myLineEdit.text())
self.window.show()
This clearly shows an important aspect: it's mandatory to always think before assigning attributes that may already exist.
In the code here above, this was actually done twice: not only we overwrote the self.ui we created before, but we also did it for window(), which is an existing function of all Qt widgets (it returns the top level ancestor window of the widget on which it was called).
As a rule of thumb, always take your time to decide how to name objects, use smart names, and consider that most common names are probably already taken: remember to check the "List of all members, including inherited members" link in the documentation of the widget type you're using, until you're experienced enough to remember them.
Solutions
The obvious solution is to use a different name for the ui of the dialog:
def createWindow(self):
self.dialog = QDialog()
self.dialog_ui = Ui_Dialog()
self.dialog_ui.setupUi(self.dialog)
self.dialog_ui.anotherLineEdit.setText(self.ui.myLineEdit.text())
self.dialog.show()
A better solution is to create a subclass for your dialog instead:
class MyDialog(QDialog):
def __init__(self, parent=None)
super().__init__(parent)
self.ui = Ui_Dialog()
self.ui.setupUi(self)
class MyWindow(QMainWindow):
# ...
def createWindow(self):
self.dialog = MyDialog()
self.dialog.ui.anotherLineEdit.setText(self.ui.myLineEdit.text())
self.dialog.show()
Also remember that another common (and, to my experience, simpler and more intuitive) method is to use multiple inheritance instead of composition:
class MyDialog(QDialog, Ui_Dialog):
def __init__(self, parent=None)
super().__init__(parent)
self.setupUi(self)
class MyWindow(QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.myLineEdit.setText('some text')
def createWindow(self):
self.dialog = MyDialog()
self.dialog.anotherLineEdit.setText(self.myLineEdit.text())
self.dialog.show()
The only issue of this approach is that it may inadvertently overwrite names of functions of the "main" widget: for instance, if you created a child widget in Designer and renamed it "window". As said above, if you always think thoroughly about the names you assign to objects, this will probably never happen (it doesn't make a lot of sense to name a widget "window").
I just created my first PyQt app used to store personnal data.
On the New Entry Dialog there is a button that when clicked, fills in QLineEdits with default values.
I would like to implement a feature so that when the mouse cursor hovers this Default button, you get a preview (probably via setPlaceholderText) of what the QLineEdits will be set to.
After looking around for a solution I came across this solution : How to Catch Hover and Mouse Leave Signal In PyQt5
to subclass the PushButton and reimplement enterEvent and leaveEvent.
However I have created my GUI with Qt Designer and am a bit confused as to how I can apply this solution since the QPushButton is created inside the Designer's .ui file where I can't really make changes...
Here's an extract of the .ui file when converted to .py with pyuic5
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
self.pushButton_contact_defaut = QtWidgets.QPushButton(self.groupBox_client)
self.pushButton_contact_defaut.setGeometry(QtCore.QRect(80, 130, 165, 22))
self.pushButton_contact_defaut.setMouseTracking(True)
self.pushButton_contact_defaut.setAutoDefault(False)
self.pushButton_contact_defaut.setObjectName("pushButton_contact_defaut")
As I said, I can't really make changes there as the code is reseted everytime I make changes to the ui file...
And here is also an extract of my main python file where I ''handle'' all the connections and logic.
I am obviously not too familiar with Python and PyQt (or anything related to programming really!)
Is there a way to ''redefine'' the PushButton from within my code and is that the best way to approach the problem, or is there something else I am missing?
class NewEntry(NE_Base, NE_Ui):
def __init__(self):
super().__init__()
QDialog.__init__(self, parent=main_window)
self.ui = NE_Ui()
self.ui.setupUi(self)
self.setWindowModality(0)
self.ui.pushButton_contact_defaut.clicked.connect(self.contact_defaut)
Thanks for your help!
EDIT : Based on musicamante's answer I got it to work just fine for my app where I have 2 buttons that "fill in" different lineEdit by doing the following.
I applied .installEventFilter(self) on both pushButton and added :
def eventFilter(self, source, event):
if event.type() == QtCore.QEvent.Enter and source == self.ui.pushButton_contact_defaut:
self.ui.contact_text.setPlaceholderText(self.contact_base)
self.ui.cell_text.setPlaceholderText(self.cell)
self.ui.email_text.setPlaceholderText(self.courriel)
if event.type() == QtCore.QEvent.Enter and source == self.ui.pushButton_copy_adress:
self.ui.street_text.setPlaceholderText(self.street)
self.ui.city_text.setPlaceholderText(self.city)
self.ui.postal_text.setPlaceholderText(self.postal)
elif event.type() == QtCore.QEvent.Leave:
self.ui.contact_text.setPlaceholderText('')
self.ui.cell_text.setPlaceholderText('')
self.ui.email_text.setPlaceholderText('')
self.ui.street_text.setPlaceholderText('')
self.ui.city_text.setPlaceholderText('')
self.ui.postal_text.setPlaceholderText('')
return super().eventFilter(source, event)
It seems a bit awkward to handle multiple pushButton this way and hopefully someone can enlighten me on that problem as well, but in the meantime, it works!
You can install an event filter on the button you want to track. An event filter is a system that "monitors" events received by the watched object and can eventually do something afterwards (including ignoring the event itself).
In your case, you'll want to check for Enter and Leave events, which are fired each time the mouse enters or leaves the widget (they are usually implemented in enterEvent and leaveEvents subclasses).
class NewEntry(QDialog, NE_Ui):
def __init__(self, parent=None):
super().__init__(parent)
# Don't do the following, is unnecessary: you already called __init__
# QDialog.__init__(self, parent=main_window)
self.ui = NE_Ui()
self.ui.setupUi(self)
self.ui.pushButton_contact_defaut.installEventFilter(self)
def eventFilter(self, source, event):
if event.type() == QEvent.Enter:
self.ui.lineEdit.setPlaceholderText('Default text')
elif event.type() == QEvent.Leave:
self.ui.lineEdit.setPlaceholderText('')
# *always* return a bool value (meaning that the event has been acted upon
# or not), it's common to call the base class implementation and then
# return the result of that
return super().eventFilter(source, event)
NEVER edit the files generated by pyuic, nor start to use them as a start for your code. As you've already found out, they're cleared each time you change the ui, and it's always better to import them as modules (or use them through uic.loadUi('somefile.ui', self)).
I have been trying to get a QComboBox in PyQt5 to become populated from a database table. The problem is trying to find a method that recognizes a click event on it.
In my GUI, my combo-box is initially empty, but upon clicking on it I wish for the click event to activate my method for communicating to the database and populating the drop-down list. It seems so far that there is no built-in event handler for a click-event for the combo-box. I am hoping that I am wrong on this. I hope someone will be able to tell me that there is a way to do this.
The best article I could find on my use-case here is from this link referring to PyQt4 QComboBox:
dropdown event/callback in combo-box in pyqt4
I also found another link that contains a nice image of a QComboBox.
The first element seems to be a label followed by a list:
Catch mouse button pressed signal from QComboBox popup menu
You can override the showPopup method to achieve this, which will work no matter how the drop-down list is opened (i.e. via the mouse, keyboard, or shortcuts):
from PyQt5 import QtCore, QtWidgets
class ComboBox(QtWidgets.QComboBox):
popupAboutToBeShown = QtCore.pyqtSignal()
def showPopup(self):
self.popupAboutToBeShown.emit()
super(ComboBox, self).showPopup()
class Window(QtWidgets.QWidget):
def __init__(self):
super(Window, self).__init__()
self.combo = ComboBox(self)
self.combo.popupAboutToBeShown.connect(self.populateConbo)
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.combo)
def populateConbo(self):
if not self.combo.count():
self.combo.addItems('One Two Three Four'.split())
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
However, for your particular use-case, I think a better solution might be to set a QSqlQueryModel on the combo-box, so that the items are updated from the database automatically.
Alternative Solution I :
We can use frame click, the code is to be used in the container of the combo box (windows/dialog/etc.)
def mousePressEvent(self, event):
print("Hello world !")
or
def mousePressEvent():
print("Hello world !")
Alternative Solution II :
We could connect a handler to the pressed signal of the combo's view
self.uiComboBox.view().pressed.connect(self.handleItemPressed)
...
def handleItemPressed(self, index):
item = self.uiComboBox.model().itemFromIndex(index)
print("Do something with the selected item")
Why would you want to populate it when it's activated rather than when the window is loaded?
I am currently developing an application with PySide (another Python binding for the Qt framework), and I populate my comboboxes in the mainwindow class __init__ function, which seems to be the way to go, judging by many examples.
Look at the example code under "QCombobox" over at Zetcode.
Firstly, I'm new to Python, Qt and PySide so forgive me if this question seems too simple.
What I'm trying to do is to display a bunch of photos in a grid in a GUI constructed using PySide API. Further, when a user clicks on a photo, I want to be able to display the information corresponding to that photo. Additionally, I would like the container/widget used for displaying the photo to allow for the photo to be changed e.g. I should be able to replace any photo in the grid without causing the entire grid of photos to be created from scratch again.
Initially I tried to use QLabel to display a QPixmap but I realized (whether mistakenly or not) that I have no way to detect mouse clicks on the label. After some searching, I got the impression that I should subclass QLabel (or some other relevant class) and somehow override QWidget's(QLabel's parent class) mousePressEvent() to enable mouse click detection. Problem is I'm not sure how to do that or whether there is any alternative widget I can use to contain my photos other than the QLabel without having to go through subclass customization.
Can anyone suggest a more suitable container other than QLabel to display photos while allowing me to detect mouse clicks on the photo or provide some code snippet for subclassing QLabel to enable it to detect mouse clicks?
Thanks in advance for any replies.
I've added an example of how to emit a signal and connect to another slot. Also the docs are very helpful
from PySide.QtCore import *
from PySide.QtGui import *
import sys
class Main(QWidget):
def __init__(self, parent=None):
super(Main, self).__init__(parent)
layout = QHBoxLayout(self)
picture = PictureLabel("pic.png", self)
picture.pictureClicked.connect(self.anotherSlot)
layout.addWidget(picture)
layout.addWidget(QLabel("click on the picture"))
def anotherSlot(self, passed):
print passed
print "now I'm in Main.anotherSlot"
class PictureLabel(QLabel):
pictureClicked = Signal(str) # can be other types (list, dict, object...)
def __init__(self, image, parent=None):
super(PictureLabel, self).__init__(parent)
self.setPixmap(image)
def mousePressEvent(self, event):
print "from PictureLabel.mousePressEvent"
self.pictureClicked.emit("emit the signal")
a = QApplication([])
m = Main()
m.show()
sys.exit(a.exec_())
Even if the question has been answered, i want to provide an other way that can be used in different situations (see below) :
from PySide.QtCore import *
from PySide.QtGui import *
import sys
class Main(QWidget):
def __init__(self, parent=None):
super(Main, self).__init__(parent)
layout = QHBoxLayout(self)
picture = QLabel()
picture.setPixmap("pic.png")
layout.addWidget(picture)
layout.addWidget(QLabel("click on the picture"))
makeClickable(picture)
QObject.connect(picture, SIGNAL("clicked()"), self.anotherSlot)
def anotherSlot(self):
print("AnotherSlot has been called")
def makeClickable(widget):
def SendClickSignal(widget, evnt):
widget.emit(SIGNAL('clicked()'))
widget.mousePressEvent = lambda evnt: SendClickSignal(widget, evnt)
a = QApplication([])
m = Main()
m.show()
sys.exit(a.exec_())
This way doesn't imply subclassing QLabel so it can be used to add logic to a widget made with QtDeigner.
Pros :
Can be used over QTdesigner compiled files
Can be applied to any kind of widget (you might need to include a super call to the overrided function to ensure widget's normal behavior)
The same logic can be used to send other signals
Cons :
You have to use the QObject syntax to connect signals and slots
I am new to the world of PyQt.I am using PyQt designer for designing the UI and coding to provide functionality in it.But unfortunately I am getting confused to link with the UI.By importing the class we generally doing in examples.But when I try my own code its not happening.
Any hints for how designer and other parts interacts will be super helpful.
Thanks in advance!
Have you tried:
class ImageViewer(QtGui.QMainWindow, ImageViewerUI.Ui_MainWindow):
because by default pyuic4 create the class Ui_MainWindow and not Ui_mainWindow
winBase, winForm = uic.loadUiType("mainWindow.ui") # this is the
file created whith Qt Designer
class Window(winBase, winForm):
def __init__(self, parent = None)
super(winBase, self).__init__(parent)
self.setupUi(self)