Abayomi Olowu
Abayomi Olowu

Reputation: 349

PYQT5 with Python

enter image description hereI'm trying to build a Python GUI app that adds information to a list with pyqt5 but I'm getting errors.the application should be able to display items that are entered into the lineedit inside the listwidget.

Below is the code:

from PyQt5 import QtWidgets, uic

app = QtWidgets.QApplication([])
form2 = uic.loadUi("login2.ui")

def add_item():
    if not form2.LineEdit_item.text() == "":
        form2.ListWidget.addItem(form2.LineEdit_item.text())
        form2.LineEdit_item.setText("")

form2.PushButton_addItem.clicked.connect(add_item)
form2.show()
app.exec()

and below is the error I'm getting:

Traceback (most recent call last):

  File "C:/Users/Windows 10/PycharmProjects/mygui2.py", line 11, in <module>
    form2.PushButton_addItem.clicked.connect(add_item)
AttributeError: 'QMainWindow' object has no attribute 'PushButton_addItem'

Process finished with exit code 1

How do i get this sorted out.

Upvotes: 0

Views: 158

Answers (1)

S. Nick
S. Nick

Reputation: 13701

Everything should work if you specify the name correctly for the objectName of theQPushButton widget.

enter image description here


enter image description here main.py

from PyQt5 import QtWidgets, uic

app = QtWidgets.QApplication([])

form2 = uic.loadUi("login2.ui")

def add_item():
    if not form2.LineEdit_item.text() == "":
        form2.ListWidget.addItem(form2.LineEdit_item.text())
        form2.LineEdit_item.setText("")

form2.PushButton_addItem.clicked.connect(add_item)
form2.show()
app.exec()

login2.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>330</width>
    <height>258</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralwidget">
   <layout class="QVBoxLayout" name="verticalLayout">
    <item>
     <widget class="QListWidget" name="ListWidget"/>
    </item>
    <item>
     <widget class="QLineEdit" name="LineEdit_item"/>
    </item>
    <item>
     <widget class="QPushButton" name="PushButton_addItem">
      <property name="text">
       <string>PushButton</string>
      </property>
     </widget>
    </item>
   </layout>
  </widget>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>330</width>
     <height>21</height>
    </rect>
   </property>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
 </widget>
 <resources/>
 <connections/>
</ui>

enter image description here

Upvotes: 2

Related Questions