原文: https://pythonspot.com/pyqt5-table/

在本文中,您将学习如何将表格与 PyQt5 结合使用。 您可以将一个或多个表格添加到任何 PyQt 应用程序或窗口。

表格可以具有多个行和列。 可以使用setRowCount()setColumnCount()来指定。

PyQt5 表格 - 图1

要添加表格,您将需要导入QTableWidgetQTableWidgetItem

示例

  1. from PyQt5.QtWidgets import QTableWidget,QTableWidgetItem

使用以下命令创建一个表格:

  1. self.tableWidget = QTableWidget()
  2. # set row count
  3. self.tableWidget.setRowCount(4)
  4. # set column count
  5. self.tableWidget.setColumnCount(2)

要添加单个单元格:

  1. self.tableWidget.setItem(X,Y, QTableWidgetItem("TEXT"))

PyQt5 表格示例

完整的 PyQt5 表格代码如下:

  1. import sys
  2. from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QAction, QTableWidget,QTableWidgetItem,QVBoxLayout
  3. from PyQt5.QtGui import QIcon
  4. from PyQt5.QtCore import pyqtSlot
  5. class App(QWidget):
  6. def __init__(self):
  7. super().__init__()
  8. self.title = 'PyQt5 table - pythonspot.com'
  9. self.left = 0
  10. self.top = 0
  11. self.width = 300
  12. self.height = 200
  13. self.initUI()
  14. def initUI(self):
  15. self.setWindowTitle(self.title)
  16. self.setGeometry(self.left, self.top, self.width, self.height)
  17. self.createTable()
  18. # Add box layout, add table to box layout and add box layout to widget
  19. self.layout = QVBoxLayout()
  20. self.layout.addWidget(self.tableWidget)
  21. self.setLayout(self.layout)
  22. # Show widget
  23. self.show()
  24. def createTable(self):
  25. # Create table
  26. self.tableWidget = QTableWidget()
  27. self.tableWidget.setRowCount(4)
  28. self.tableWidget.setColumnCount(2)
  29. self.tableWidget.setItem(0,0, QTableWidgetItem("Cell (1,1)"))
  30. self.tableWidget.setItem(0,1, QTableWidgetItem("Cell (1,2)"))
  31. self.tableWidget.setItem(1,0, QTableWidgetItem("Cell (2,1)"))
  32. self.tableWidget.setItem(1,1, QTableWidgetItem("Cell (2,2)"))
  33. self.tableWidget.setItem(2,0, QTableWidgetItem("Cell (3,1)"))
  34. self.tableWidget.setItem(2,1, QTableWidgetItem("Cell (3,2)"))
  35. self.tableWidget.setItem(3,0, QTableWidgetItem("Cell (4,1)"))
  36. self.tableWidget.setItem(3,1, QTableWidgetItem("Cell (4,2)"))
  37. self.tableWidget.move(0,0)
  38. # table selection change
  39. self.tableWidget.doubleClicked.connect(self.on_click)
  40. @pyqtSlot()
  41. def on_click(self):
  42. print("\n")
  43. for currentQTableWidgetItem in self.tableWidget.selectedItems():
  44. print(currentQTableWidgetItem.row(), currentQTableWidgetItem.column(), currentQTableWidgetItem.text())
  45. if __name__ == '__main__':
  46. app = QApplication(sys.argv)
  47. ex = App()
  48. sys.exit(app.exec_())

下载 PyQT5 示例