【问题标题】:Use QThread to periodically update a QTableWidget pyqt使用 QThread 定期更新一个 QTableWidget pyqt
【发布时间】:2014-07-10 06:45:42
【问题描述】:

在我的应用程序中,我使用 API 调用获取记录,然后将数据动态添加到 QTableWidget。到目前为止,这是我的代码的 sn-p:

class TriageUI(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.ui = Ui_TriageWindow()
        self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
        self.move(QtGui.QApplication.desktop().screen().rect().center()- self.rect().center())
        self.ui.setupUi(self)
        self.update_records()        

    def update_records(self):
        #items are the results from the API fetch
        items = json.loads(get_triage_queue(COOKIES, SERVER, PORT))
        rows = len(items['objects'])
        self.ui.tableWidget.setColumnCount(5)
        self.ui.tableWidget.setRowCount(rows)
        index = 0
        column = 0
        for j in items['objects']:
            for key, value in j.iteritems():
                f = QtGui.QTableWidgetItem(str(value))
                self.ui.tableWidget.setItem(index, column, QtGui.QTableWidgetItem(f))
                column = column + 1

但是,我希望能够定期(例如 15 秒后)对数据进行 API 调用,然后将结果中的任何新数据项添加到表中。我怎样才能做到这一点。

提前谢谢你。

【问题讨论】:

  • 你应该看看QTimer

标签: python pyqt pyqt4 qtablewidget


【解决方案1】:

这里有一个使用PyQt4.QtCore.QTimer 重复调用类成员函数(可能是你的update_records 函数)的示例。有时,问题的解决方案比我们想象的要容易。

注意函数startstop。此功能使您可以随意启动和停止计时器。

from PyQt4 import QtGui as gui
from PyQt4 import QtCore as core


class Blinker(gui.QWidget):
    def __init__(self, parent=None):
        super(Blinker, self).__init__(parent)

        self.label = gui.QLabel(self)
        self.label.setFixedSize(200, 200)
        self.layout = gui.QHBoxLayout(self)
        self.layout.addWidget(self.label)

        self.timer  = core.QTimer(self)
        self.timer.setInterval(1000)          # Throw event timeout with an interval of 1000 milliseconds
        self.timer.timeout.connect(self.blink) # each time timer counts a second, call self.blink
        self.color_flag = True

    def start(self):
        self.timer.start()

    def stop(self):
        self.timer.stop()

    @core.pyqtSlot()
    def blink(self):
        if self.color_flag:
            self.label.setStyleSheet("background-color: blue;")
        else:
            self.label.setStyleSheet("background-color: yellow;")
        self.color_flag = not self.color_flag


if __name__ == '__main__':
    import sys
    app = gui.QApplication(sys.argv)

    w = Blinker()
    w.show()
    w.start()

    sys.exit(app.exec_())

【讨论】:

  • 只是一个简单的问题。如何在新的Qthread中进行接口更新操作?
  • 好吧,现在我想到了一个简单的想法。您可以继承 QThread 类并添加自定义信号。让我们称它为 retreive_data 甚至 its_time,然后您可以将此信号连接到一些 slot,例如 update_records,这样您就可以获得与 QTimer 相同的机制.使用信号槽方法从线程内更新 GUI 是一种不好的做法。在 QThread 中使用 QTimer 也有一些复杂性,请参阅:qt-project.org/forums/viewthread/26159
  • 谢谢。我会看看的。
猜你喜欢
  • 2017-03-15
  • 1970-01-01
  • 1970-01-01
  • 2016-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-21
相关资源
最近更新 更多