I have 3 Qlabels: label1, label2 and label3.
My idea is this: when mouse hover label1 or label2, label3.text will show 'mouse on label1' or 'mouse on label2' according to which label got mouse hovered.
I created a subclass 'CustomLabel' for label1 and label2, where I define the enterEvent function.
The problem is that I can't access label3 from that class.
MainWindow.ui.label3 is impossible to reach!
Here is the code, everything is working except that one line of code where I didnt manage to get access to label3.
I am a very beginner so probably I am missing something very simple.
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(688, 446)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.label1 = CustomLabel(self.centralwidget)
self.label1.setGeometry(QtCore.QRect(110, 110, 121, 31))
self.label1.setObjectName("label1")
self.label2 = CustomLabel(self.centralwidget)
self.label2.setGeometry(QtCore.QRect(320, 110, 121, 31))
self.label2.setObjectName("label2")
self.label3 = QtWidgets.QLabel(self.centralwidget)
self.label3.setGeometry(QtCore.QRect(190, 280, 121, 31))
self.label3.setObjectName("label3")
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.label1.setText(_translate("MainWindow", "Label1"))
self.label2.setText(_translate("MainWindow", "Label2"))
self.label3.setText(_translate("MainWindow", "Label3"))
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
class CustomLabel(QtWidgets.QLabel):
def __init__(self,texte):
Custom_font = QtGui.QFont()
Custom_font.setPointSize(14)
super(CustomLabel,self).__init__(texte)
self.setFont(Custom_font)
def enterEvent(self,e):
print('here is ',self.text())
MainWindow.ui.label3.setText('mouse on ', self.text) # Error on this line, 'MainWindow' has no attribute ui
#MainWindow.label3.setText('mouse on ', self.text) # Error here too, 'MainWindow' has no attribute label3
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())
"MainWindow.ui.label3 is impossible to reach" because label3 does not exist, nor does ui.
MainWindow is a class, a "template" for an instance.
So, the MainWindow class object has no attribute called ui (therefore, no ui.label3 also), but the mainWindow instance you create near the end of your code does.
To achieve what you want, there are at least two methods.
Use signals/slots to allow communication between the instances
Create a signal for the CustomLabel class, and emit it whenever the mouse enters it; then connect that signal from the main window:
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.label1.entered.connect(self.labelEntered)
self.ui.label2.entered.connect(self.labelEntered)
def labelEntered(self, label):
self.ui.label3.setText('mouse on {}'.format(label.text()))
class CustomLabel(QtWidgets.QLabel):
entered = QtCore.pyqtSignal(object)
def __init__(self,texte):
Custom_font = QtGui.QFont()
Custom_font.setPointSize(14)
super(CustomLabel,self).__init__(texte)
self.setFont(Custom_font)
def enterEvent(self,e):
self.entered.emit(self)
Use an event filter to catch events
In this case, we install an event filter on the widgets we want to watch for events, and if that event is a mouse enter one, we'll update the third label accordingly:
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.label1.installEventFilter(self)
self.ui.label2.installEventFilter(self)
def eventFilter(self, source, event):
if isinstance(source, CustomLabel) and event.type() == QtCore.QEvent.Enter:
# the "source" of the event is one of our custom labels, and the event
# type is an "Enter" one, so let's update the other label
self.ui.label3.setText('mouse on {}'.format(source.text()))
return super(MainWindow, self).eventFilter(source, event)
As a side note, it seems that you're trying to edit the contents of a file generated from pyuic (or, at least, you're probably trying to mimick their behavior). This is something that should never be done, as those files are only meant to be used as imported modules in your actual program (and their mimicking their behavior is not the best way to create your GUI from code).
Read more about using Designer to understand the correct ways to use files created by Designer.
If you need to extend the default Qt widgets by subclassing and you need to use those classes on Designer, do some research about using "promoted widgets".
Related
This question already has answers here:
QtDesigner changes will be lost after redesign User Interface
(2 answers)
Closed 2 years ago.
I'm new to Python and I've searched for an answer but couldn't find it (or rather couldn't properly implement it).
I've generated a window with a few buttons in QtDesigner's file named "arch.ui", converted to arch.py.
As I'll be updating GUI occasionally, I don't want to create functions in arch.py, so I've created a main.py file for that.
I've a problem with linking button click to a function => I try to link "btnSource" (from arch.py) to function "printMe" (in main.py).
Obviously it doesn't work. Any help welcome.
Here is generated Designer file:
# Form implementation generated from reading ui file 'arch.ui'
#
# Created by: PyQt5 UI code generator 5.15.0
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(460, 233)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.btnSource = QtWidgets.QPushButton(self.centralwidget)
self.btnSource.setGeometry(QtCore.QRect(80, 60, 75, 23))
self.btnSource.setObjectName("btnSource")
self.lblSource = QtWidgets.QLabel(self.centralwidget)
self.lblSource.setGeometry(QtCore.QRect(180, 60, 511, 21))
self.lblSource.setObjectName("lblSource")
self.lblTarget = QtWidgets.QLabel(self.centralwidget)
self.lblTarget.setGeometry(QtCore.QRect(180, 120, 481, 16))
self.lblTarget.setObjectName("lblTarget")
self.btnTarget = QtWidgets.QPushButton(self.centralwidget)
self.btnTarget.setGeometry(QtCore.QRect(80, 120, 75, 23))
self.btnTarget.setObjectName("btnTarget")
self.btnGo = QtWidgets.QPushButton(self.centralwidget)
self.btnGo.setGeometry(QtCore.QRect(280, 120, 75, 23))
self.btnGo.setObjectName("btnGo")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 460, 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)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.btnSource.setText(_translate("MainWindow", "Source"))
self.lblSource.setText(_translate("MainWindow", "TextLabel"))
self.lblTarget.setText(_translate("MainWindow", "TextLabel"))
self.btnTarget.setText(_translate("MainWindow", "Target"))
self.btnGo.setText(_translate("MainWindow", "Go"))
And here is my main.py file:
from PyQt5 import QtCore, QtGui, QtWidgets
from arch import Ui_MainWindow
import sys
app = QtWidgets.QApplication(sys.argv)
class myWindow(Ui_MainWindow):
def __init__(self):
super(myWindow, self).__init__()
self.btnSource.clicked.connect(self.btnSource.printMe)#
def printMe(self):
print('blah blah blah')
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
tl;dr
Subclass from both QMainWindow and Ui_MainWindow, and call setupUi from there; then create an instance of myWindow:
class MyWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super(MyWindow, self).__init__()
self.setupUi(self)
self.btnSource.clicked.connect(self.printMe)
def printMe(self):
print('blah blah blah')
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
mainWindow = MyWindow()
mainWindow.show()
sys.exit(app.exec_())
Explanation
Your code doesn't work for many reasons; while the main problem might be that you actually never created an instance of myWindow (about that, you should always use capitalized names for classes), making it completely useless, it wouldn't have worked anyway.
That's because you should not subclass from the ui class object, but from the QWidget descendant (QMainWindow, in your case) you're going to use.
The ui_* objects created from pyuic are only intended as a high level (and unmodified) interface to create the UI on top of a QWidget subclass.
Calling setupUi(something) actually creates all child widgets for the widget something, sets the layout and, possibly, automatically connects to slots with a compatible name, but that's all: in fact, if you closely look at the code from the ui file, it actually does nothing besides setupUi and retranslateUi (nor it should!): there's not even an __init__!
If you need to add interaction and create connections from signals to slot/functions, you should use the single/multiple inheritance approaches as explained in the official guide about using Designer with PyQt; the only other possibility is to use loadUi (while still subclassing from the base class) with the source .ui file:
from PyQt5 import QtWidgets, uic
class MyWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
uic.loadUi('path/to/gui.ui', self)
self.someWidget.someSignal.connect(self.someSlot)
# ...
def someSlot(self, signalArguments, [...]):
# do something...
PS: for various reasons, it's usually better to run a QApplication only if the script is the one that's been run (hence the if __name__ ...), mostly because there should be just only one QApplication instance for every running program; in any case, it shouldn't be created before the class declarations (unless, you really know what you're doing); it's not a big deal in your case, but, as usual, better safe than sorry.
I'm trying to use an interface I designed in Qt designer as a means of letting the user edit preferences for my program.
I am currently able to display the GUI I made by connecting the following function to the preferences menu option:
def preferences(self):
preferences_dialog = QtGui.QDialog()
preferences_dialog.ui = Ui_Preferences()
preferences_dialog.ui.setupUi(preferences_dialog)
preferences_dialog.setAttribute(QtCore.Qt.WA_DeleteOnClose)
preferences_dialog.exec_()
My question is this: what is a good way to implement this so that I can use the fields in the GUI to change values in my config file?
I also want to display the pre-existing values in the boxes before they are changed.
Should I make a new class that uses the above function as its __init__ method? I would imagine I might need a class that handles all of the processes for the window. Also, I am unsure of a good way to pass data between the file and the GUI without a bunch of specific code.
Use QSettings. Here's an example in PyQt5.
First, the main window's ui definition
# file ui_main.py
from PyQt5 import QtCore, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(584, 897)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 584, 21))
self.menubar.setObjectName("menubar")
self.menuPreferences = QtWidgets.QMenu(self.menubar)
self.menuPreferences.setObjectName("menuPreferences")
MainWindow.setMenuBar(self.menubar)
self.setPreferencesAction = QtWidgets.QAction(MainWindow)
self.setPreferencesAction.setObjectName("setPreferencesAction")
self.menuPreferences.addAction(self.setPreferencesAction)
self.menubar.addAction(self.menuPreferences.menuAction())
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.menuPreferences.setTitle(_translate("MainWindow", "Settings"))
self.setPreferencesAction.setText(_translate("MainWindow", "Preferences"))
and second, the preferences dialog ui definition:
# file ui_dialog.py
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(508, 300)
self.buttonBox = QtWidgets.QDialogButtonBox(Dialog)
self.buttonBox.setGeometry(QtCore.QRect(150, 250, 341, 32))
self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
self.buttonBox.setObjectName("buttonBox")
self.sl_value = QtWidgets.QSlider(Dialog)
self.sl_value.setGeometry(QtCore.QRect(220, 120, 161, 31))
self.sl_value.setOrientation(QtCore.Qt.Horizontal)
self.sl_value.setObjectName("sl_value")
self.buttonBox.accepted.connect(Dialog.accept)
self.buttonBox.rejected.connect(Dialog.reject)
QtCore.QMetaObject.connectSlotsByName(Dialog)
The MainWindow keeps track of the configuration in a QSettings object, which is uniquely defined (and accessed) using the application and company strings fed into its constructor.
# file main.py
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.settings = QSettings(COMPANY_NAME, APPLICATION_NAME)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
when the preferences dialog box is triggered, the settings are loaded and passed along to the PreferencesDialog. If the Dialog returns successfully, the new settings are saved and written to storage using del
#pyqtSlot(bool)
def on_setPreferencesAction_triggered(self, triggered):
settings = self.settings
default_config_value = settings.value(CONFIG_KEY_1, defaultValue=None, type=str)
preference_dialog = PreferencesDialog(default_config_value=default_config_value, parent=self)
if preference_dialog.exec():
settings.setValue(CONFIG_KEY_1, preference_dialog.preferences[CONFIG_KEY_1])
# this writes the settings to storage
del settings
The PreferencesDialog constructor sets the values according to the parameters it receives, and a a pyqtSlot is attached to the appropriate signal to save the values in a dictionary.
To run the demo:
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
I would like to display a window with a QwebView widget in Pyside. For this I use some code generated by QtCreator:
#code generated by QtCreator:
from PySide import QtCore, QtGui
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(400, 300)
self.centralWidget = QtGui.QWidget(MainWindow)
self.centralWidget.setObjectName("centralWidget")
self.webView = QtWebKit.QWebView(self.centralWidget)
self.webView.setGeometry(QtCore.QRect(10, 20, 380, 270))
self.webView.setUrl(QtCore.QUrl("file:///C:/pdf_folder/test.pdf"))
self.webView.setObjectName("webView")
MainWindow.setCentralWidget(self.centralWidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8))
from PySide import QtWebKit
# My code:
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
if __name__ == "__main__":
APP = QtGui.QApplication(sys.argv)
MW = MainWindow()
MW.show()
sys.exit(APP.exec_())
I am sure to have a pdf file in the specified path, but when I run my script, the pdf file is never displayed in my window.
Do you know what I am doing wrong ?
I saw this topic Is it possible to get QWebKit to display pdf files?, but the answer don't work for me (after changing PyQt to Pyside in the import lines).
I also saw this topic PDF with QWebView: missing refresh/repaint after loading, the workaround (using a timer before loading) work for me. however I don't think that using a timer to load a file is a good way to solve the problem.
And, mainly, the code that I used for Ui_MainWindow is generated with QtCreator, I didn't change it and I don't want to change it by myself (without using QtCreator). It is just a simple form for a window with only one widget QtWebKit.QWebView in which I want to load a file. It should work without weird workaround. Why the code automatically generated don't work ? Am I using QtCreator in a wrong way ?
You have to enable QWebView's plugins:
self.webView = QtWebKit.QWebView(self.centralWidget)
self.webView.settings().setAttribute(QWebSettings.PluginsEnabled, True)
also try to set the QWebView URL after showing the main window.
MW = MainWindow()
MW.show()
MW.ui.webView.setUrl(QtCore.QUrl("file:///C:/pdf_folder/test.pdf"))
I think the paint events has to do with the fact you don't see the pdf file.
I Created a code using pyQt Designer in ui and changed it to py code.
Now i want to add some Keypress events to my this i.e. say if i click on keyboard key with numeric 3 , my label should have text 3 on it or it just print "Hi"
I have already checked a lot of forums over internet and found that its best to reimplement keyPressEvent to use keyboard events . I tried that however somehow i am not able to make it work in the code generated by pyQT designer .
Below is the code generated by pyQT designer . I have put the code of keyPressEvent re implementation in it as well , however it dosent work :
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(800, 600)
MainWindow.setFocus()
def keyPressEvent(self, qKeyEvent):
print "hi"
print(qKeyEvent.key())
if qKeyEvent.key() == QtCore.Qt.Key_Return:
print('Enter pressed')
else:
super(Ui_MainWindow).keyPressEvent(qKeyEvent)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.horizontalLayoutWidget = QtGui.QWidget(self.centralwidget)
self.horizontalLayoutWidget.setGeometry(QtCore.QRect(40, 10, 721, 80))
self.horizontalLayoutWidget.setObjectName(_fromUtf8("horizontalLayoutWidget"))
self.horizontalLayout = QtGui.QHBoxLayout(self.horizontalLayoutWidget)
self.horizontalLayout.setMargin(0)
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.textEdit = QtGui.QLabel(self.centralwidget)
self.textEdit.setGeometry(QtCore.QRect(50, 110, 81, 41))
self.textEdit.setObjectName(_fromUtf8("textEdit"))
self.pushButton = QtGui.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(130, 260, 75, 23))
self.pushButton.setObjectName(_fromUtf8("pushButton"))
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
self.menubar.setObjectName(_fromUtf8("menubar"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.textEdit.setText("I am a label")
self.pushButton.setText(_translate("MainWindow", "PushButton", None))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
I am new to this forum , it will be helpful if someone can help . I know this can be achieved by creating another class who inherits QMainWindow but i want to do this in the same code i.e in the code block generated by pyQT Designer .
Also please suggest If there is any way to do this without reimplementing keypressEvent
Thanks
There are two reasons why your code doesn't work.
The first is that you are defining keyPressEvent inside the setupUi method, hence it is completely invisible to the class.
Secondly because in the code:
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
You are creating an instance of QMainWindow, which uses its own implementation of keyPressEvent. You should create a subclass of QMainWindow and reimplement the method there.
How to properly do this.
Open the designer and create your mainwindow.
compile the .ui file using pyuic:
$pyuic4 mainwindow.ui -o ui_mainwindow.py
Create a new file where you'll write the subclass of the QMainWindow, mymainwindow.py. Do no modify ui_mainwindow.py. There is a big warning at the start of the file:
# WARNING! All changes made in this file will be lost!
If you don't want to lose all your code when changing the UI then do not modify the file.
Implement the keyPressEvent in the subclass:
from PyQt4 import QtGui
# import the UI from the generated file
from ui_mainwindow import Ui_MainWindow
# it's not stricly necessary to subclass Ui_MainWindow.
class MyMainWindow(QtGui.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(MyMainWindow, self).__init__(parent)
self.setupUi(self)
# if you didn't subclass Ui_MainWindow simply do:
# Ui_MainWindow().setupUi(self)
def keyPressEvent(self, event):
# implement the method here
self.label.setText(self.label.text() + 'a')
if __name__ == '__main__':
app = QtGui.QApplication([])
win = MyMainWindow()
win.show()
app.exec_()
Finally run the code and note that every time you press a key an a is added to the text.
I couldn't understand the connectSlotsByName() method which is predominently used by pyuic4.. As far the class is single in a PyQt file it's ok since we can use self which will be associated with a single object throughout.. But when we try to use various classes from different files the problem and the need to use connectSlotsByName() arises.. Here's what i encountered which is weird..
I created a stacked widget..
I placed my first widget on it.. It
has a button called "Next >".
On clicking next it hides the current
widget and adds another widget which has the "click me" button..
The problem here is the click event for "click me" button in second is not captured.. It's a minimal example that i can give for my original problem.. Please help me..
This is file No.1..(which has the parent stacked widget and it's first page). On clicking next it adds the second page which has "clickme" button in file2..
from PyQt4 import QtCore, QtGui
import file2
class Ui_StackedWidget(QtGui.QStackedWidget):
def __init__(self,parent=None):
QtGui.QStackedWidget.__init__(self,parent)
self.setObjectName("self")
self.resize(484, 370)
self.setWindowTitle(QtGui.QApplication.translate("self", "stacked widget", None, QtGui.QApplication.UnicodeUTF8))
self.createWidget1()
def createWidget1(self):
self.page=QtGui.QWidget()
self.page.setObjectName("widget1")
self.pushButton=QtGui.QPushButton(self.page)
self.pushButton.setGeometry(QtCore.QRect(150, 230, 91, 31))
self.pushButton.setText(QtGui.QApplication.translate("self", "Next >", None, QtGui.QApplication.UnicodeUTF8))
self.addWidget(self.page)
QtCore.QMetaObject.connectSlotsByName(self.page)
QtCore.QObject.connect(self.pushButton,QtCore.SIGNAL('clicked()'),self.showWidget2)
def showWidget2(self):
self.page.hide()
obj=file2.widget2()
obj.createWidget2(self)
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
ui = Ui_StackedWidget()
ui.show()
sys.exit(app.exec_())
Here's file2
from PyQt4 import QtGui,QtCore
class widget2():
def createWidget2(self,parent):
self.page = QtGui.QWidget()
self.page.setObjectName("page")
self.parent=parent
self.groupBox = QtGui.QGroupBox(self.page)
self.groupBox.setGeometry(QtCore.QRect(30, 20, 421, 311))
self.groupBox.setObjectName("groupBox")
self.groupBox.setTitle(QtGui.QApplication.translate("self", "TestGroupBox", None, QtGui.QApplication.UnicodeUTF8))
self.pushButton = QtGui.QPushButton(self.groupBox)
self.pushButton.setGeometry(QtCore.QRect(150, 120, 92, 28))
self.pushButton.setObjectName("pushButton")
self.pushButton.setText(QtGui.QApplication.translate("self", "Click Me", None, QtGui.QApplication.UnicodeUTF8))
self.parent.addWidget(self.page)
self.parent.setCurrentWidget(self.page)
QtCore.QMetaObject.connectSlotsByName(self.page)
QtCore.QObject.connect(self.pushButton,QtCore.SIGNAL('clicked()'),self.printMessage)
def printMessage(self):
print("Hai")
Though in both the widgets(i mean pages)
QtCore.QMetaObject.connectSlotsByName(self.page)
the clicked signal in second dialog isn't getting processed. Thanks in advance.. Might be a beginner question..
A better question is "Why not just use new-style signals and slots?". They're much simpler and don't require any weird naming conventions:
from sys import argv, exit
from PyQt4 import QtCore, QtGui
class MyWidget(QtGui.QWidget):
def __init__(self, parent=None):
super(MyWidget, self).__init__(parent)
self._layout = QtGui.QVBoxLayout()
self.setLayout(self._layout)
self._button = QtGui.QPushButton()
self._button.setText('Click NOW!')
self._layout.addWidget(self._button)
self._button.clicked.connect(self._printMessage)
#QtCore.pyqtSlot()
def _printMessage(self):
print("Hai")
if __name__ == "__main__":
app = QtGui.QApplication(argv)
main = MyWidget()
main.show()
exit(app.exec_())
At first, here is the minimal working example:
from sys import argv, exit
from PyQt4 import QtCore, QtGui
class widget2(QtGui.QWidget):
def __init__(self, args):
self.app = MainApp(args)
QtGui.QWidget.__init__(self)
self.setObjectName('I')
self._layout = QtGui.QVBoxLayout(self)
self.setLayout(self._layout)
self.pushButtoninWidget2 = QtGui.QPushButton(self)
self.pushButtoninWidget2.setObjectName("pushButtoninWidget2")
self.pushButtoninWidget2.setText('Click NOW!')
self._layout.addWidget(self.pushButtoninWidget2)
QtCore.QMetaObject.connectSlotsByName(self)
#QtCore.pyqtSlot()
def on_pushButtoninWidget2_clicked(self):
print("Hai")
class MainApp(QtGui.QApplication):
def __init__(self, args):
QtGui.QApplication.__init__(self, args)
if __name__ == "__main__":
main = widget2(argv)
main.show()
exit(main.app.exec_())
When you trying to connect slots by name, you must give proper names to the slots and then someone (moc, uic, or you by calling connectSlotsByName) must connect them. Proper name for such a slot is: "on_PyQtObjectName_PyQtSignalName".
Note, that, if I'd omitted #QtCore.pyqtSlot() in the example, slot would be executed once for every appropriate overload (twice in this case).
You DO need to call connectSlotsByNames directly, cause there is no moc, which do it for you when you use QT in C++, and you do not use uic and .ui file. If you want to connect slots implicitly (I'm always doing so, except slots, connected directly in .ui), you'd better use more pytonish syntaxe: button.clicked.connect(self._mySlot).
And take a look at https://riverbankcomputing.com/static/Docs/PyQt5/signals_slots.html#connecting-slots-by-name
You do not need to call connectSlotsByName(), just remove those lines.
In file2, calling QtCore.QMetaObject.connectSlotsByName(self.page) tries to do this:
QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL('clicked()'), self.on_pushButton_clicked())
That will not work for you since self.on_pushBotton_clicked() slot is not defined.
I find it is easiest to create your own connections in PyQt... I recommend removing the calls to connectSlotsByName from your both classes... you do not need it.
Also, your wdiget1 class should set the name of it's pushButton (preferably something other then "pushButton" to avoid confusion with the button in widget2).
Thank you so much jcoon for your reply.. But after a very long time banging my head against the wall i found the solution..
The problem was..
self.obj=test_reuse_stacked1.widget2()
self.obj.createWidget2(self)
instead of obj..
Here is #MarkVisser's QT4 code updated to QT5:
from sys import argv, exit
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QApplication, QWidget
class MyWidget(QWidget):
def __init__(self, parent=None):
super(MyWidget, self).__init__(parent)
self._layout = QtWidgets.QVBoxLayout()
self.setLayout(self._layout)
self._button = QtWidgets.QPushButton()
self._button.setText('Click NOW!')
self._layout.addWidget(self._button)
self._button.clicked.connect(self._print_message)
#QtCore.pyqtSlot()
def _print_message(self):
print("Hai")
if __name__ == "__main__":
app = QApplication(argv)
main = MyWidget()
main.show()
exit(app.exec_())
Another minimal working example with Qt for Python aka PySide2/6.
Key ingredients:
widget to connect MUST have .setObjectName
function to connect MUST be decorated with #QtCore.Slot()
both objects (function AND widget) MUST be members of passed object (self here)
from PySide2 import QtCore, QtWidgets
# or from PySide6 import QtCore, QtWidgets
class Widget(QtWidgets.QWidget):
def __init__(self):
super(Widget, self).__init__()
layout = QtWidgets.QVBoxLayout(self)
self.button = QtWidgets.QPushButton(self)
self.button.setObjectName('button')
self.button.setText('Click Me!')
layout.addWidget(self.button)
QtCore.QMetaObject.connectSlotsByName(self)
#QtCore.Slot()
def on_button_clicked(self):
print(f'Hai from {self.sender()}')
if __name__ == '__main__':
app = QtWidgets.QApplication([])
main = Widget()
main.show()
app.exec_()
I couldn't get mit any smaller really 🤔