无法从 QTableWidget 中选择整行数据 [英] Can't select entire row of data from QTableWidget

查看:74
本文介绍了无法从 QTableWidget 中选择整行数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题陈述

我正在尝试从我的 QtableWidget 中选择数据行并将它们打印到我的控制台,这样我就可以测试一些东西,最终目标是能够绘制数据.但是我永远无法获取整行数据.

背景

我制作了一个 GUI,可以通过导入特定格式的 CSV 文件来嵌入多个 QTableWidget.目标是能够从相同或不同表的多行中提取数据,然后以并排方式绘制它们.每一行数据都是自己的数据集,有自己的图,但同一个图上会有多个图.

为了完成这项任务,我制作了一个名为 CompareWindow 的窗口,当按下名为Compare"的 Qpushbutton 时,该窗口会打开.该窗口提示用户输入表格的名称以及他们希望绘制的表格中的相应行.

提交此信息后,我有可以参考的字典,其中保存了所有已实例化的 QTableObject.其中键是给连接到相应表对象的表的名称.

问题

我尝试抓取行数据的两种主要方法是……

第一个想法是使用 TableObject.selectRow() 命令,我会遍历我想要的行,但是每当我这样做时,它都会返回一个 nonetype.

我尝试的第二种方法是迭代给定的行列,以便通过附加项目值来一个一个地填充列表.但是,当我这样做时,它只会重复使用相同的数字填充列表,这是我 Qtable 中的第一个单元格.

即使我明确调用某个行或列,我也会得到相同的输出.被拉出的输出是 .12,这是我的 CSV 文件中第一个单元格的数字.

这是我遇到问题的相关代码.

 def initialMultiPlot(self, tableV, rowV, PlotV):"""1. 将 TableName 值与 TableDB 中的键值匹配2. 当我们找到匹配项时,查看该键对应的表对象,并进行迭代通过对象行并选择由 rowV 指定的行3.调用这些值的图"""#调用我的类并创建一个空白图形,最终我们将在其上绘制数据f = CreateFigure.FigureAssembly()打印("")对于表V中的我:"""tableV:是表示分配的表名的字符串列表 [Table1, Table2, Table3]rowV:是一个列表,包含代表用户希望绘制的相应表格中的行的列表.例如 [[1,2],[3,4],[1]] 表示 table1 中的第 1,2 行,table2 中的第 3,4 行......等等PlotV:是一个字符串,它是一个盒子"或胡须",用于说明要绘制的方法.现在默认是做一个简单的箱线图"""print("创建表实例")#Table Dictionary 设置所以表的名称(tableV)是字典的键#和实际的表对象被这些键引用self.TableOBJ = self.TableDictionary[i]print("表对象的数据类型是…………{}".format(type(self.TableOBJ)))#将存储我们行数据的空列表self.Elements = []尝试:对于 rowV 中的行:对于 i 在行中:print("rowV 值为... {}".format(rowV))打印(当前行列表{}".格式(行))print("i 值为 {}".format(i))打印(迭代")对于范围内的 j(self.TableOBJ.columnCount()):print("i 值为 ...{}".format(i))print("j 值为 .... {}".format(j))#FIRST 想法尝试选择整行数据print("i 值为 ...{}".format(i))print("j 值为 .... {}".format(j))#整行返回无类型EntireRow = self.TableOBJ.selectRow(i)打印(整行)#selecteditems#SECOND 想法尝试使用 for 循环并遍历行中的每个值item = self.TableOBJ.itemAt(i,j)#explicit 调用 (row 1, col 1) 和 (row 3, col 3),两者都输出 .12打印(self.TableOBJ.itemAt(1,1).text())打印(self.TableOBJ.itemAt(3,3).text())print("打印项目...... {}".format(item))元素 = item.text()打印(元素)#.12 的列表self.Elements.append(元素)#elements = [self.TableOBJ.item(i, j).text() for j in range(self.TableOBJ.columnCount()) if# self.TableOBJ.item(i, j).text() != ""]#打印(元素)除了作为 e 的例外:打印(e)打印(自我.元素)

这是包含我所有文件的 GitHub 链接:https://github.com/Silvuurleaf/Data-Visualize-Project

问题出现在我的文件 Perspective.py 中的方法initialMultiPlot 中.文件 CompareWindow.py 向我的 Perspective.py 发送信号并连接到 initateMultiPlot.如果有什么需要更深入的解释,请询问.

解决方案

根据 文档:

<块引用>

QTableWidgetItem *QTableWidget::itemAt(int ax, int ay) const

返回相当于QPoint(ax, ay)的位置的itemtable 小部件的坐标系,如果指定点,则返回 0未被表格小部件中的项目覆盖.

也就是说,返回给定的项 x 和 y,它们是相对于 QTableWidget 的图形坐标,显然不是您要查找的.

您必须使用 item():

<块引用>

QTableWidgetItem *QTableWidget::item(int row, int column) const

如果已设置,则返回给定行和列的项目;否则返回 0.

但在您的情况下,除非您进行以下更改,否则将无法使用:

class CreateTable(QTableWidget):....对于范围内的 j (0, m):self.item = QTableWidgetItem(str(round(ValList[j], 6)))# print("{}, {}".format(i, j))self.setItem(i, j, self.item)

到:

class CreateTable(QTableWidget):....对于范围内的 j (0, m):item = QTableWidgetItem(str(round(ValList[j], 6)))# print("{}, {}".format(i, j))self.setItem(i, j, item)

也就是说,您将 self.item 更改为 item.

问题是乍一看这个错误比较难,QTableWidget类有一个item()函数,但是当你使用self.item语句时正在替换该调用,即当 python 读取该语句时,它将使用属性而不是函数,因此您会收到错误:

<块引用>

TypeError 'xxx' 对象不可调用

Problem Statement

I'm trying to select rows of data from my QtableWidget and print them out to my console just so I can test some things, with the end goal being able to plot the data. However I can never grab the whole row of data.

Background

I have made a GUI that can embed several QTableWidgets by importing a specifically formatted CSV file. The goal is to be able to pull data from multiple rows from the same or different tables and then plot them in a side by side fashion. Where each row of data will be its own dataset and have its own plot, but there will be multiple plots on the same figure.

To complete this task I have made a window called CompareWindow that opens when a Qpushbutton called "Compare" is pressed. The window prompts the user to type in the names of the tables and the respective rows from that table they wish to plot.

After this information is submitted I have dictionary that I can reference which has saved all the QTableObjects that have been instantiated. Where the keys are the names given to the tables which are connected to their corresponding Table Object.

Problem

The two main methods I have tried to grab the row data are…

The first idea was using TableObject.selectRow() command I would iterate through the rows I wanted, but whenever I did this to it would return a nonetype.

The second method I tried was to iterate a given rows columns so it would fill a list one by one by appending the item values. However when I did this it only filled the list with the same number repeatedly, which was the first cell in my Qtable.

Even when I explicitly called a certain row or column I would get the same output. The output being pulled is .12, the number from the first cell in my CSV file.

Here is the code in question I'm having problems with.

    def initiateMultiPlot(self, tableV, rowV, PlotV):
    """
        1. Match TableName values with the key values in our TableDB
        2. When we find a  match look at that key's corresponding Table Object, and iterate
        through that objects rows and select the rows specified by rowV
        3.Call plot for those values

    """

    #calls my class and creates a blank figure where eventually we will plot data on
    f = CreateFigure.FigureAssembly()
    print("")
    for i in tableV:
        """
            tableV: is list of strings that represent assigned tablenames [Table1, Table2, Table3]
            rowV: is a list, containing lists representing rows from corresponding Tables the user wishes to plot.
                for example [[1,2],[3,4],[1]] means rows 1,2 from table1, rows 3,4 from table2... so on
            PlotV: is a string that is ethier "box" or "whisker" to tell what method to plot. Default right now 
            is to do a simple boxplot
        """
        print("Creating table instance")

        #Table Dictionary is setup so the names of the Tables (tableV) are the keys of the dictionary
        #and the actual table objects are referenced by these keys
        self.TableOBJ = self.TableDictionary[i]
        print("Data Type for the table object is..................{}".format(type(self.TableOBJ)))

        #empty list that will store our row data
        self.Elements = []
        try:
            for rows in rowV:

                for i in rows:
                    print("rowV value is... {}".format(rowV))
                    print("current row list{}".format(rows))
                    print("i value is {}".format(i))
                    print("itterating")

                    for j in range(self.TableOBJ.columnCount()):
                        print("i value is ...{}".format(i))
                        print("j value is .... {}".format(j))

                        #FIRST idea try selecting entire row of data
                        print("i value is ...{}".format(i))
                        print("j value is .... {}".format(j))

                        #entire row returns none-type
                        EntireRow = self.TableOBJ.selectRow(i)
                        print(EntireRow)

                        #selecteditems

                        #SECOND idea try using for loop and iterating through every value in a row
                        item = self.TableOBJ.itemAt(i,j)

                        #explicit call for (row 1, col 1) and  (row 3, col 3), both which output .12
                        print(self.TableOBJ.itemAt(1,1).text())
                        print(self.TableOBJ.itemAt(3,3).text())
                        print("printing item...... {}".format(item))
                        element = item.text()
                        print(element)

                        #list of .12
                        self.Elements.append(element)

                    #elements = [self.TableOBJ.item(i, j).text() for j in range(self.TableOBJ.columnCount()) if
                    #            self.TableOBJ.item(i, j).text() != ""]
                    #print(elements)

        except Exception as e:
            print(e)

        print(self.Elements)

Here is my GitHub link containing all my files: https://github.com/Silvuurleaf/Data-Visualize-Project

The problem occurs in my file Perspective.py in the method initiateMultiPlot. The file CompareWindow.py sends a signal to my Perspective.py and is connected to initateMultiPlot. Please inquire if anything requires more in depth explanation.

解决方案

According to the documentation:

QTableWidgetItem *QTableWidget::itemAt(int ax, int ay) const

Returns the item at the position equivalent to QPoint(ax, ay) in the table widget's coordinate system, or returns 0 if the specified point is not covered by an item in the table widget.

That is, returns the given item x and y which are graphical coordinates with respect to QTableWidget, and clearly is not what you are looking for.

You must use the item():

QTableWidgetItem *QTableWidget::item(int row, int column) const

Returns the item for the given row and column if one has been set; otherwise returns 0.

But in your case will not work unless you do the following change:

class CreateTable(QTableWidget):
     ....
            for j in range(0, m):
                self.item = QTableWidgetItem(str(round(ValList[j], 6)))
                # print("{}, {}".format(i, j))
                self.setItem(i, j, self.item)

to:

class CreateTable(QTableWidget):
     ....
            for j in range(0, m):
                item = QTableWidgetItem(str(round(ValList[j], 6)))
                # print("{}, {}".format(i, j))
                self.setItem(i, j, item)

That is, you change your self.item to item.

The problem is that at first glance the error is rather difficult, the QTableWidget class has an item() function, but when you use the self.item statement you are replacing that call, ie when python reads that statement it will use the attribute and not the function , So you get the error:

TypeError 'xxx' object is not callable

这篇关于无法从 QTableWidget 中选择整行数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆