【问题标题】:Unable to populate QTableWidget无法填充 QTableWidget
【发布时间】:2015-06-03 21:07:03
【问题描述】:

我正在尝试填充 QTableWidget(设置行数和列数,添加列名并向单元格添加数据),但小部件显示为空且未引发错误。

这是工作示例,请参阅类 TableForm():

from PyQt4 import QtCore, QtGui


try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_TableForm(object):
    def setupUi(self, TableForm):
        TableForm.setObjectName(_fromUtf8("TableForm"))
        TableForm.resize(495, 506)
        TableForm.setLocale(QtCore.QLocale(QtCore.QLocale.Russian, QtCore.QLocale.RussianFederation))
        self.verticalLayout = QtGui.QVBoxLayout(TableForm)
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
        self.table_widget = QtGui.QTableWidget(TableForm)
        self.table_widget.setRowCount(0)
        self.table_widget.setColumnCount(0)
        self.table_widget.setObjectName(_fromUtf8("table_widget"))
        self.verticalLayout.addWidget(self.table_widget)
        self.horizontalLayout = QtGui.QHBoxLayout()
        self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
        self.start_edit_button = QtGui.QPushButton(TableForm)
        self.start_edit_button.setObjectName(_fromUtf8("start_edit_button"))
        self.horizontalLayout.addWidget(self.start_edit_button)
        self.save_edits_buttonBox = QtGui.QDialogButtonBox(TableForm)
        self.save_edits_buttonBox.setEnabled(False)
        self.save_edits_buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Save)
        self.save_edits_buttonBox.setObjectName(_fromUtf8("save_edits_buttonBox"))
        self.horizontalLayout.addWidget(self.save_edits_buttonBox)
        self.verticalLayout.addLayout(self.horizontalLayout)

        self.retranslateUi(TableForm)
        QtCore.QMetaObject.connectSlotsByName(TableForm)

    def retranslateUi(self, TableForm):
        TableForm.setWindowTitle(_translate("TableForm", "Таблица", None))
        self.start_edit_button.setText(_translate("TableForm", "Редактировать", None))




class TableForm(QtGui.QDialog, Ui_TableForm):


  def __init__(self):
    super(TableForm, self).__init__()
    self.ui = Ui_TableForm()
    self.ui.setupUi(self)
    data = [['name1', 'name2'], {'name1':[1], 'name2':[2]}, 2]
    col_names = data[0]
    col_data = data[1]
    rows = data[2] + 1
    cols = len(col_names)
    self.ui.table_widget.setRowCount(rows)
    self.ui.table_widget.setColumnCount(cols)
    self.ui.table_widget.setHorizontalHeaderLabels(col_names)
    n = 0
    for key in col_names:
      m = 0
      for item in col_data[key]:
        newitem = QtGui.QTableWidgetItem(item)
        self.ui.table_widget.setItem(m, n, newitem)
        m += 1
      n += 1


if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    dialog = QtGui.QDialog()
    u = TableForm()
    u.setupUi(dialog)
    dialog.show()
    sys.exit(app.exec_())

怎么了?

【问题讨论】:

    标签: python python-2.7 qt4 pyqt4 qtablewidget


    【解决方案1】:

    您混合了几种将 ui 添加到对话框的不同方式。表填充被第二次调用 setupUi 覆盖,这会将行和列重置为零。

    我已经在下面的代码中修复了这个问题,并且还纠正了一些其他问题(参见 cmets):

    # no need to inherit Ui_TableForm
    class TableForm(QtGui.QDialog):
      def __init__(self):
        super(TableForm, self).__init__()
        self.ui = Ui_TableForm()
        self.ui.setupUi(self)
        data = [['name1', 'name2'], {'name1':[1], 'name2':[2]}, 2]
        col_names = data[0]
        col_data = data[1]
        rows = data[2] + 1
        cols = len(col_names)
        self.ui.table_widget.setRowCount(rows)
        self.ui.table_widget.setColumnCount(cols)
        self.ui.table_widget.setHorizontalHeaderLabels(col_names)
        # use enumerate
        for n, key in enumerate(col_names):
          for m, item in enumerate(col_data[key]):
            # item content must always be strings
            newitem = QtGui.QTableWidgetItem(str(item))
            self.ui.table_widget.setItem(m, n, newitem)
    
    if __name__ == "__main__":
        import sys
        app = QtGui.QApplication(sys.argv)
        # ui setup is all done in __init__
        dialog = TableForm()
        dialog.show()
        sys.exit(app.exec_())
    

    【讨论】:

    • 感谢您的帮助,但我还有另一个问题。另一个setupUi 调用的原因是这是我发现从该函数启动TableForm() 的唯一方法。考虑函数def showTab(): dialog = TableForm() \ dialog.show()。如果代码底部的第 2 行和第 3 行被替换为 showTab(),则该小部件根本不会出现。我应该如何从函数中调用TableForm()
    • 好的,我想通了:在showTab() 我应该添加d = dialog.exec_() 行。
    猜你喜欢
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    • 2013-03-03
    • 2020-09-28
    • 1970-01-01
    • 2022-06-13
    • 2013-09-12
    相关资源
    最近更新 更多