如何删除pyqt4(qtable小部件)中的整行

时间:2018-08-31 05:47:10

标签: python python-2.7 pyqt pyqt4

在这里,当我尝试删除所选的行时,出现以下错误:

  

“ TypeError:QAbstractItemModel.removeRow()的参数1具有无效的类型”。

我在pyqt的qtablewidget中删除了正确的删除行/行的正确方法进行了很多搜索。但是,我无法删除所选的行/行。

能否请您分享用于删除pyqt的qtablewidget中选定行/行的示例代码?

import sys
from functools import partial
from PyQt4 import QtGui, QtCore


class Example(QtGui.QWidget):
    def __init__(self):
        super(Example, self).__init__()
        self.initUI()

    def initUI(self):
        self. table = QtGui.QTableWidget(self)
        self.table.setGeometry(10,70, 600,300)
        self.table.setRowCount(3)
        self.table.setColumnCount(6)

        self.table.verticalHeader().hide()
        self.table.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)

        fnt = self.table.font()
        fnt.setPointSize(11)
        self.table.setFont(fnt)

        self.table.setHorizontalHeaderLabels(("S.no, Item,Qty,Rate(Rs:),total,"",").split(','))

        all_data = [("1", "xxx", 10, 0),
                    ("2", "yyy", 20, 0),
                    ("3", "zzz", 30, 0)]

        for r, row_data in enumerate(all_data):
            for c, value in zip((0, 1, 3), row_data):
                it = QtGui.QTableWidgetItem(str(value))
                self.table.setItem(r, c, it)

        for r in range(self.table.rowCount()):

            spin = QtGui.QSpinBox(minimum=0, maximum=50)
            spin.valueChanged.connect(partial(self.calculateSubTotal, r))
            self.table.setCellWidget(r, 2, spin)

            btn = QtGui.QPushButton(icon=QtGui.QIcon("trash1.png"))
            self.table.setCellWidget(r, 5, btn)
            # selected = self.table.selectedItems()
            # btn.clicked.connect(self.remove)

        self.setWindowTitle("table")
        self.setGeometry(200, 300, 400, 300)
        self.show()
    # def remove(self,row):
        # self.table.removeRow(self.table.currentRow)    

    def calculateSubTotal(self, row, value):
        rate = float(self.table.item(row, 3).text())
        subtotal = value * rate

        item_subtotal = self.table.item(row, 4)
        if item_subtotal is None:
            item_subtotal = QtGui.QTableWidgetItem()
            self.table.setItem(row, 4, item_subtotal)

        item_subtotal.setText(str(subtotal))

def main():
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_()) 


if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:1)

您的语法几乎是正确的,请尝试添加方括号:

self.table.removeRow(self.table.currentRow())