I'm writing some GUI and then I want to add text to a listView. Right now I just want to add "hello" to figure it out, and then I will grow it from there.
Here is a sample of my code:
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
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(584, 461)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.lineEdit_6 = QtGui.QLineEdit(self.centralwidget)
self.lineEdit_6.setGeometry(QtCore.QRect(72, 210, 171, 20))
....
self.retranslateUi(MainWindow)
QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8("clicked()")), MainWindow.addEntry)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
....
def addEntry(self):
listView.Items.Add("Hello")
Then to open it:
from PyQt4 import *
import signal
import sys
from PyQt4.QtGui import QApplication, QMessageBox
from inv_window import *
def main():
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
When trying to run this I get:
AttributeError: 'QMainWindow' object has no attribute 'addEntry'
Any ideas on how I can rectify this? I've tried googling but I'm having a difficult time nailing down a solution
The problem appears to be on this line:
QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8("clicked()")), MainWindow.addEntry)
Your MainWindow variable is a QMainWindow instance, and so it doesn't have the addEntry method which belongs to your Ui_MainWindow class. Hence the error you see.
I'd like to point out a stylistic issue with your code, if I may. In Python, names of local variables and method/function parameters conventionally start with a lower-case letter. You have a variable (and method parameter) named MainWindow. When I first read your code I got confused because MainWindow looked to me like the name of a class. I would recommend changing the name of this variable/method parameter to mainWindow or main_window or mainwin or suchlike.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With