簡體   English   中英

有沒有辦法通過它在網格中的位置刪除小部件或刪除該網格中的行?

[英]Is there any way to delete widget by its position in grid or delete row in this grid?

我需要能夠通過 .addWidget 創建無限的小部件(在網格中,新小部件 - 新行)。 這東西我已經有了。 但我還需要按他的位置刪除小部件的能力。 我試過這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM