Generating keyPressEvent in a code generated by pyQT Designer - python

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.

Related

How to link Qt Designer button to a function in a separate file [duplicate]

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.

How to access MainWindow.Widget from a subclass?

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".

Qt Python GUI Crashes on Button Click

The code is smaller version I put together to demonstrate what I am trying to do. I just need to get information from a QButtonGroup of radio buttons. Specifically the text of which one has been clicked. However, when I run click the button in the GUI python crashes. There is no error message so I can't pinpoint the cause. Below is the example code, below that is the image show upon clicking a radio button:
Working earlier with a more inefficient method I got to sending commands to the server however the same error occurred when I tried to save the changes to the couchDB document specifically using db.save(doc) command.
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'test.ui'
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(400, 300)
self.verticalLayoutWidget = QtWidgets.QWidget(Dialog)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(130, 80, 101, 80))
self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
self.verticalLayout.setContentsMargins(0, 0, 0, 0)
self.verticalLayout.setObjectName("verticalLayout")
self.rad2 = QtWidgets.QRadioButton(self.verticalLayoutWidget)
self.rad2.setObjectName("rad2")
self.group1 = QtWidgets.QButtonGroup(Dialog)
self.group1.setObjectName("group1")
self.group1.addButton(self.rad2)
self.verticalLayout.addWidget(self.rad2)
self.rad3 = QtWidgets.QRadioButton(self.verticalLayoutWidget)
self.rad3.setObjectName("rad3")
self.group1.addButton(self.rad3)
self.verticalLayout.addWidget(self.rad3)
self.rad1 = QtWidgets.QRadioButton(self.verticalLayoutWidget)
self.rad1.setObjectName("rad1")
self.group1.addButton(self.rad1)
self.verticalLayout.addWidget(self.rad1)
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def printText(button):
print(button.text())
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.rad2.setText(_translate("Dialog", "RadioButton"))
self.rad3.setText(_translate("Dialog", "RadioButton"))
self.rad1.setText(_translate("Dialog", "RadioButton"))
ui.group1.buttonClicked.connect(self.printText)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Dialog = QtWidgets.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec_())
You need to define the slot with a self argument:
def printText(self, button):
print(button.text())

Implementing a preferences dialog window in PyQt

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_())

Qt Framework, PyQt5 and AttributeError: 'MyApp' object has no attribute 'myAttribute'

Last week I started to learn Python and I developed some command line apps. Now I would like to develop apps with GUI. I searched in internet and I found a project that fits my needs: Qt Project (http://qt-project.org) and PyQt (http://www.riverbankcomputing.com/software/pyqt/intro). I installed Qt 5.3.2 Open Source, SIP 4.16.4, PyQt5 5.3.2 on Mac OS X 10.10 and python 2.7.6. After some troubles on installing Qt and PyQt, finally I managed to make them work. If I open example projects from PyQt example folder the gui appears without any problems. So I created my GUI with Qt Creator and then I used pyuic5 to generate python code. This is what pyuic5 created (file name "myapp_auto.py"):
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/Users/andrea/Developer/Qt/mainwindow.ui'
#
# Created: Mon Nov 17 14:20:14 2014
# by: PyQt5 UI code generator 5.3.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(400, 300)
self.centralWidget = QtWidgets.QWidget(MainWindow)
self.centralWidget.setObjectName("centralWidget")
self.ok = QtWidgets.QPushButton(self.centralWidget)
self.ok.setGeometry(QtCore.QRect(140, 120, 115, 32))
self.ok.setAccessibleName("")
self.ok.setObjectName("ok")
self.text = QtWidgets.QLabel(self.centralWidget)
self.text.setGeometry(QtCore.QRect(100, 70, 181, 16))
self.text.setAccessibleName("")
self.text.setAlignment(QtCore.Qt.AlignCenter)
self.text.setObjectName("text")
self.time = QtWidgets.QDateTimeEdit(self.centralWidget)
self.time.setGeometry(QtCore.QRect(100, 180, 194, 24))
self.time.setAccessibleName("")
self.time.setObjectName("time")
MainWindow.setCentralWidget(self.centralWidget)
self.menuBar = QtWidgets.QMenuBar(MainWindow)
self.menuBar.setGeometry(QtCore.QRect(0, 0, 400, 22))
self.menuBar.setObjectName("menuBar")
self.menuMyApp = QtWidgets.QMenu(self.menuBar)
self.menuMyApp.setObjectName("menuMyApp")
self.menuEdit = QtWidgets.QMenu(self.menuBar)
self.menuEdit.setObjectName("menuEdit")
MainWindow.setMenuBar(self.menuBar)
self.mainToolBar = QtWidgets.QToolBar(MainWindow)
self.mainToolBar.setObjectName("mainToolBar")
MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.mainToolBar)
self.statusBar = QtWidgets.QStatusBar(MainWindow)
self.statusBar.setObjectName("statusBar")
MainWindow.setStatusBar(self.statusBar)
self.menuBar.addAction(self.menuMyApp.menuAction())
self.menuBar.addAction(self.menuEdit.menuAction())
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.ok.setText(_translate("MainWindow", "Ok"))
self.text.setText(_translate("MainWindow", "I\'m a GUI"))
self.menuMyApp.setTitle(_translate("MainWindow", "MyApp"))
self.menuEdit.setTitle(_translate("MainWindow", "Edit"))
After that I added a new python file where I put my code; this is what i wrote (file name "myapp.py"):
#!/usr/bin/env python
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from myapp_auto import Ui_MainWindow
import sys
import time
class MyApp(Ui_MainWindow):
parse_triggered = pyqtSignal()
def __init__(self, parent=None, name=None):
Ui_MainWindow.__init__(self)
if __name__ == "__main__":
app = QApplication(sys.argv)
MainWindow = QMainWindow()
ui = MyApp()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
Then, I run myapp.py and I verified that all GUI elements appeared to be where they should be. Well...now arrive my issue: I tried to access with code the "time" element in MainWindow modifying init def thus:
def __init__(self, parent=None, name=None):
Ui_MainWindow.__init__(self)
# Set the date to now
now = QDateTime()
now.setTime_t(int(time.time()))
self.time.setDateTime(now)
But the compiler shows alway this error:
AttributeError: 'MyApp' object has no attribute 'time'
This happen even if I try to access any other element ("ok", "text").
Will surely be a stupid mistake but I just can not figure out where I went wrong.
Thank you all guys!
Have a good day,
Andrea
You're not far off.
The MyApp class needs to inherit QMainWindow, and you don't need to use the time module. Try something like this:
class MyApp(QMainWindow, Ui_MainWindow):
parse_triggered = pyqtSignal()
def __init__(self, parent=None, name=None):
super(MyApp, self).__init__(parent)
self.setupUi(self)
# Set the date to now
self.time.setDateTime(QDateTime.currentDateTime())
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MyApp()
window.show()
sys.exit(app.exec_())

Categories

Resources