【问题标题】:How to get data from hidden 'id' column in QtableWidget如何从 QtableWidget 中隐藏的“id”列获取数据
【发布时间】:2021-04-12 10:28:31
【问题描述】:

使用 qTableWidget 查看我的 sqlite 数据库条目。 数据库的第一列是隐藏的,因为它是自动分配给条目的 ID。

现在我希望用户选择他想要删除的行,然后能够按下删除按钮。 我正在使用以下方法来做到这一点:

class StartScherm(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        super(StartScherm, self).__init__()
        self.setupUi(self)
        self.database_laden()
        # -- Button presses with .connect -- #
        
        self.tableSnelleKijk.doubleClicked.connect(self.weergave_scherm)
        self.tableSnelleKijk.setSelectionBehavior(
            QtWidgets.QTableView.SelectRows)
        self.tableSnelleKijk.setColumnHidden(0, True)

现在我正在尝试创建一个函数,一旦用户单击 GUI 中的删除按钮,该函数就会读取 ID,以便我可以将其从 sqlite 数据库中删除。我用这个:

def delete(self):
        index = self.tableSnelleKijk.selectedItems()
        print(index[0].text())

不幸的是,这给了我第一个可见的列数据作为文本而不是带有 ID 的隐藏列。

如何访问隐藏数据?

编辑:将列更改为行 数据库仅隐藏在 tableview 中,在 sqlite 中它只是有一个 rowID 我可以用来访问当前行以删除/编辑。

数据库代码:

c.execute("""CREATE TABLE Medailles (
            id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
            orde text,
            periode text,
            locatie text,
            beschrijving text
            )""")

使用 .setColumnHidden 将列隐藏在 QtableView 中。 当用户决定输入一个新条目时,数据库会被填充,这是处理这个问题的函数:

def add(self):
        orde = self.orde_comboBox.currentText()
        periode = self.periode_input.text()
        locatie = self.locatie_input.text()
        beschrijving = self.beschrijving_input.toPlainText()

        medaille = Medaille(orde, periode, locatie, beschrijving)
        with conn:
            c.execute("INSERT INTO Medailles (orde, periode, locatie, beschrijving) VALUES (:orde, :periode, :locatie, :beschrijving)", {
                'orde': medaille.orde, 'periode': medaille.periode, 'locatie': medaille.locatie, 'beschrijving': medaille.beschrijving})
        self.close()

【问题讨论】:

    标签: python pyqt5 qt-designer


    【解决方案1】:

    如果数据位于不可见列中,则无法选择该列中的项目。您可以使用sibling(row, column) 函数(或siblingAtColumn(column) 用于Qt>=5.11)访问这些索引(及其数据):

        def delete(self):
            rows = set()
            for index in self.tableSnelleKijk.selectedItems():
                id = index.sibling(index.row(), 0).text()
                rows.add(id)
            print('IDs to delete: {}'.format(sorted(rows)))
    

    请注意,如果您需要将数据写入数据库或编辑其布局,您应该考虑使用带有QtSql.QSqlTableModel 的基本 QTableView,否则您可能会遇到一些不一致、错误甚至数据损坏的情况。对您的实施非常小心。

    【讨论】:

    • 非常感谢。我想我最好像你提到的那样使用 QSqlTableModel,因为它是一个从集合中添加、编辑、删除项目的程序。干杯!
    【解决方案2】:

    要获取 QTableWidget (PyQt5) 中隐藏列的值:

    row = self.tblWidget.currentRow()
    col = position of hidden column - usually 0
    ID  = self.tblWidget.item(row,col).text()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-15
      • 2018-06-08
      • 1970-01-01
      • 2011-11-02
      • 1970-01-01
      • 2020-01-26
      • 2018-09-17
      • 2012-06-02
      相关资源
      最近更新 更多