如何连续更改一些QTableWidget项?

时间:2013-02-01 03:57:03

标签: python qt pyqt pyside qtablewidget

我有一个包含以下列的QTableWidget:

    Username    Password     URL       Status
   +----------+-----------+---------+---------+
   |  user1   |  passwd1  | url.com |   OK    |
   |  user2   |  passwd2  | url.com |   FAIL  |
   +----------+-----------+---------+---------+

在我的应用程序中的工作人员QThread中,会发出一个信号,其中包含表格中显示的数据。但是,此数据需要稍后更新(特别是“状态”列)。

我希望能够更新,例如,仅更新第二行。现在,到目前为止,我将循环遍历表中的所有行,然后尝试将某个唯一字段(例如用户名)与软件发送的数据进行匹配。因此,如果第2行的状态需要从“FAIL”更新为“RETRY”,则发送到GUI线程的信号将包含用户名和状态字符串。然后,我将比较两个字符串(信号中的一个,即QThread与当前表中的那些字符串),如果匹配,则更新表。希望这是有道理的。

事情是,我想知道这是否是一个可行的解决方案?还有别的吗?我考虑在QTableWidget中添加另一个“隐藏”列,它将包含由每个QThread生成的随机字符串,然后将更新。但原则仍然是一样的。

有人可以给我任何指示吗?

编辑:为每个请求添加代码:

这是我的GUI线程代码(搜索和更新部分):

def writeToMainTable(self, param):

    username = param['username']
    statusText = param['statusText']

    for i in xrange(self.mainTable.currentRowCount()):
        if username == self.mainTable.item(i, 0).text():
            found = True
            activerow = i    

    if found:
        if statusText is not None: self.mainTable.setItem(activerow, 3, QTableWidgetItem(statusText))

虽然QThread有这样的东西:

def sendToTable(self, param): #param is a dict here as well
    self.mainsig.emit(param)

2 个答案:

答案 0 :(得分:0)

我不确定你想要什么。我假设你想让Qt为你做循环?如果是这样,这是一种方式。希望这会有所帮助。

import sys

from PySide.QtCore import *
from PySide.QtGui import *

class Main(QWidget):

    def __init__(self):
        super(Main, self).__init__()

        self.table = Table(self)
        self.change = QPushButton('Change')

        layout = QHBoxLayout(self)

        layout.addWidget(self.table)
        layout.addWidget(self.change)

        self.change.clicked.connect(self.table.updateCell)

class Table(QTableWidget):

    def __init__(self, parent=None):
        super(Table, self).__init__(2, 2, parent)
        self.setItem(1, 0, QTableWidgetItem('test'))
        self.setItem(1, 1, QTableWidgetItem('False'))

    def updateCell(self):

        item, = self.findItems('test', Qt.MatchExactly)
        new = repr(not eval(self.item(item.row(), 1).text()))
        self.item(row, 1).setText(new)


app = QApplication([])  
main = Main()
main.show()
app.exec_()

答案 1 :(得分:0)

您似乎使用其他QThread来更新每一行,因此您可以使用QSignalMapper,如下所示:

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import time, random

from PyQt4 import QtGui, QtCore

class MyThread(QtCore.QThread):
    statusChanged = QtCore.pyqtSignal()

    def __init__(self, parent=None):
        super(MyThread, self).__init__(parent)
        self.status = None

    def run(self):
        time.sleep(3)
        self.status = True if not self.status else False
        self.statusChanged.emit()


class MyWindow(QtGui.QWidget):
    def __init__(self, parent=None):
        super(MyWindow, self).__init__(parent)

        self.tableWidget = QtGui.QTableWidget(self)
        self.tableWidget.setRowCount(2)
        self.tableWidget.setColumnCount(4)
        self.tableWidget.horizontalHeader().setResizeMode(QtGui.QHeaderView.Stretch)

        self.signalMapper = QtCore.QSignalMapper(self)  
        self.signalMapper.mapped.connect(self.on_signalMapper_mapped)  

        for row in range(2):
            status = random.getrandbits(1)
            state  = "Ok" if status else "Failed"
            thread = MyThread(self)
            thread.status = status

            self.signalMapper.setMapping(thread, row)

            thread.statusChanged.connect(self.signalMapper.map)
            thread.start()

            values = ["user", "passwd", "url.com", state]
            for column, value in enumerate(values):
                item = QtGui.QTableWidgetItem()
                item.setText("{0}: {1}".format(row, value))

                self.tableWidget.setItem(row, column, item)

        self.gridLayout = QtGui.QGridLayout(self)
        self.gridLayout.addWidget(self.tableWidget, 0, 0)

    @QtCore.pyqtSlot(int)
    def on_signalMapper_mapped(self, number):
        state  = "Ok" if self.signalMapper.mapping(number).status else "Failed"
        item   = self.tableWidget.item(number, 3)
        item.setText("{0}: {1}".format(number, state))

if __name__ == "__main__":
    import sys

    app = QtGui.QApplication(sys.argv)
    app.setApplicationName('MyWindow')

    main = MyWindow()
    main.resize(666, 111)
    main.show()

    sys.exit(app.exec_())