简体   繁体   中英

Dynamically add and remove widgets by pyqt5

I am creating a calorie counting app. There was a problem with dynamically adding and removing widgets. I need to add a new product by clicking on the button (label "product", label "weight", and fields for entering the name of the product and weight. I have no ideas. Tell me how to implement this feature? Here's the code (it's just a skeleton with no implementations to show what I'm using):

import sys  # interaction with Python

from PyQt5.QtWidgets import *  # for classic application based on widgets
from PyQt5 import uic  # to read ui file
from PyQt5 import QtWidgets  # to create gui


class MyWin(QtWidgets.QMainWindow):  # create class witch inherit QMainWindow
    def __init__(self):  # constructor
        QtWidgets.QMainWindow.__init__(self)  # constructor of parent class
        uic.loadUi("gui.ui", self)  # load ui


if __name__ == '__main__':  # for check non import module
    app = QApplication(sys.argv)  # create app
    mw = MyWin()  # create object of MyWin class
    mw.show()  # to show gui
    sys.exit(app.exec_())  # execute app

gui:

<?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>458</width>
    <height>234</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralwidget">
   <layout class="QVBoxLayout" name="verticalLayout">
    <item>
     <widget class="QGroupBox" name="breakfest">
      <property name="title">
       <string>Breakfest</string>
      </property>
      <layout class="QVBoxLayout" name="verticalLayout_3">
       <item>
        <layout class="QVBoxLayout" name="verticalLayout_2">
         <item>
          <layout class="QHBoxLayout" name="horizontalLayout_2">
           <item>
            <widget class="QLabel" name="label_product">
             <property name="text">
              <string>Product</string>
             </property>
            </widget>
           </item>
           <item>
            <widget class="QLabel" name="label_weight">
             <property name="text">
              <string>Weight</string>
             </property>
            </widget>
           </item>
          </layout>
         </item>
         <item>
          <layout class="QHBoxLayout" name="horizontalLayout">
           <item>
            <widget class="QLineEdit" name="lineEdit_product"/>
           </item>
           <item>
            <widget class="QLineEdit" name="lineEdit_weight"/>
           </item>
          </layout>
         </item>
         <item>
          <spacer name="verticalSpacer">
           <property name="orientation">
            <enum>Qt::Vertical</enum>
           </property>
           <property name="sizeHint" stdset="0">
            <size>
             <width>20</width>
             <height>40</height>
            </size>
           </property>
          </spacer>
         </item>
         <item>
          <layout class="QHBoxLayout" name="horizontalLayout_3">
           <item>
            <widget class="QPushButton" name="add_product">
             <property name="text">
              <string>Add product</string>
             </property>
            </widget>
           </item>
           <item>
            <widget class="QPushButton" name="remove_product">
             <property name="text">
              <string>Remove product</string>
             </property>
            </widget>
           </item>
          </layout>
         </item>
        </layout>
       </item>
      </layout>
     </widget>
    </item>
   </layout>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
 </widget>
 <resources/>
 <connections/>
</ui>

Connect the clicked signal to add/remove the fields. Here is how you could use the same "structure" as the first product/weight field from your ui file.

class MyWin(QtWidgets.QMainWindow):  # create class witch inherit QMainWindow
    def __init__(self):  # constructor
        QtWidgets.QMainWindow.__init__(self)  # constructor of parent class
        uic.loadUi("gui.ui", self)  # load ui
        self.add_product.clicked.connect(self.add)
        self.remove_product.clicked.connect(self.remove)

    def add(self):
        h1 = QHBoxLayout()
        h1.addWidget(QLabel('Product'))
        h1.addWidget(QLabel('Weight'))
        h2 = QHBoxLayout()
        h2.addWidget(QLineEdit())
        h2.addWidget(QLineEdit())
        i = self.verticalLayout_2.count()
        self.verticalLayout_2.insertLayout(i - 2, h1)
        self.verticalLayout_2.insertLayout(i - 1, h2)

    def remove(self):
        i = self.verticalLayout_2.count()
        if i > 3:
            QWidget().setLayout(self.verticalLayout_2.takeAt(i - 3))
            QWidget().setLayout(self.verticalLayout_2.takeAt(i - 4))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM