Python 是否有任何方法可以通过小部件在网格中的位置来删除小部件或删除该网格中的行?
我需要有能力通过.addWidget(在网格中,newwidget-newrow)创建无限的小部件。我已经有了。但我也需要能够删除他的位置小部件。我试过这个:Python 是否有任何方法可以通过小部件在网格中的位置来删除小部件或删除该网格中的行?,python,python-3.x,pyqt,pyqt5,Python,Python 3.x,Pyqt,Pyqt5,我需要有能力通过.addWidget(在网格中,newwidget-newrow)创建无限的小部件。我已经有了。但我也需要能够删除他的位置小部件。我试过这个: from PyQt5 import QtWidgets, QtGui from PyQt5.QtCore import QTime, QTimer, QObject from PyQt5.QtWidgets import QMainWindow, QApplication, QLCDNumber, QPushButton, QGridLa
from PyQt5 import QtWidgets, QtGui
from PyQt5.QtCore import QTime, QTimer, QObject
from PyQt5.QtWidgets import QMainWindow, QApplication, QLCDNumber, QPushButton, QGridLayout, QLabel, QLineEdit, QTextEdit, QGroupBox
import sys
from somethingtestui import Ui_MainWindow
global selection
selection = 1
class mywindow(QtWidgets.QMainWindow):
def __init__(self):
super(mywindow, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.pushButton.clicked.connect(self.add)
def add(self):
global selection
self.row = QTextEdit('')
self.text3 = QPushButton('Delete row')
self.ui.gridLayout.addWidget(self.row, selection, 0, 1, 1)
self.ui.gridLayout.addWidget(self.text3, selection, 1, 1, 1)
# global delf
def delf():
global selection
selection = selection-1
number = self.ui.gridLayout.itemAtPosition(selection,1)
print(number)
self.row.deleteLater()
self.rrow = None
self.text3.deleteLater()
self.text3 = None
self.text3.clicked.connect(delf)
selection = selection+1
app = QtWidgets.QApplication([])
application = mywindow()
application.show()
sys.exit(app.exec())
有了它,我可以添加许多小部件。如果有一个创建的小部件,我可以随意删除并重复它。但如果有2个或更多已创建的小部件,我可以删除其中一个,然后单击另一行中的“删除”按钮,它将崩溃:
Traceback (most recent call last):
File "E:\Programs\YandexDisk\Tempfiles\TournamentBot\testi22.py", line 31, in delf
self.row.deleteLater()
RuntimeError: wrapped C/C++ object of type QTextEdit has been deleted
我为自己找到了解决办法
from somethingtestui import Ui_MainWindow
global rowcnt
rowcnt = 1
class mywindow(QtWidgets.QMainWindow):
def __init__(self):
super(mywindow, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.pushButton.clicked.connect(self.add)
self.ui.gridLayout.setRowMinimumHeight(50,50)
self.ui.gridLayout.setColumnMinimumWidth(50,50)
def add(self):
global rowcnt
self.row = QTextEdit('')
self.delbtn = QPushButton('Delete row')
self.ui.gridLayout.addWidget(self.row, rowcnt, 0, 1, 1)
self.ui.gridLayout.addWidget(self.delbtn, rowcnt, 1, 1, 1)
w = self.ui.gridLayout.itemAtPosition(rowcnt,1).widget()
def delf(currow):
global rowcnt
rowcnt = rowcnt-1
number = self.ui.gridLayout.itemAtPosition(currow,1).widget()
number2 = self.ui.gridLayout.itemAtPosition(currow,0).widget()
number.deleteLater()
number2.deleteLater()
w.clicked.connect(lambda: delf(mrowcnt))
rowcnt = rowcnt+1
mrowcnt = rowcnt-1
试图使用全局变量跟踪布局中小部件的索引几乎总是一个坏主意。此外,当一个项目从网格布局中删除时,其他项目将重新编号,因此如果稍后删除一个小部件,它在布局中的索引可能与添加到布局时的索引不同。与其删除小部件,不如隐藏它们。