QTableWidget控件换成QTableView 控件 并在其中添加两个表并设置为水平布局
时间: 2024-05-16 15:13:04 浏览: 22
可以使用QTableView控件和QStandardItemModel模型来实现这个功能。下面是代码示例:
```python
from PyQt5.QtWidgets import QApplication, QWidget, QTableView, QHeaderView, QHBoxLayout
from PyQt5.QtGui import QStandardItemModel, QStandardItem
app = QApplication([])
window = QWidget()
# 创建第一个表格
model1 = QStandardItemModel(4, 3)
model1.setHorizontalHeaderLabels(['Name', 'Age', 'Gender'])
for row in range(4):
for column in range(3):
item = QStandardItem('Cell %s,%s' % (row, column))
model1.setItem(row, column, item)
table1 = QTableView()
table1.setModel(model1)
table1.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
# 创建第二个表格
model2 = QStandardItemModel(3, 4)
model2.setHorizontalHeaderLabels(['ID', 'Phone', 'Email', 'Address'])
for row in range(3):
for column in range(4):
item = QStandardItem('Cell %s,%s' % (row, column))
model2.setItem(row, column, item)
table2 = QTableView()
table2.setModel(model2)
table2.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
# 创建水平布局并添加表格
layout = QHBoxLayout()
layout.addWidget(table1)
layout.addWidget(table2)
window.setLayout(layout)
window.show()
app.exec_()
```
在这个示例中,我们首先创建了两个QStandardItemModel模型,并用它们来创建两个QTableView控件。然后我们使用QHBoxLayout布局来将这两个表格放置在同一行中,并将布局设置为窗口的主要布局。
最后,我们展示了窗口并启动了应用程序事件循环。注意,在此示例中,我们将两个表格的列宽设置为自适应模式,以便它们可以自动调整大小以适应其内容。