pyqt tablewidget点击界面出新界面
时间: 2023-08-15 09:02:38 浏览: 112
PyQt是一种用于创建图形用户界面(GUI)应用程序的Python模块。通过使用PyQt的TableWidget部件,我们可以实现点击界面时出现新界面的需求。
首先,我们需要导入PyQt的相关模块,如下所示:
```python
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QTableWidget, QTableWidgetItem
from PyQt5.QtCore import Qt
import sys
```
接下来,我们创建一个主窗口类`MainWindow`,继承自`QMainWindow`。在该类的初始化方法中,我们创建一个`TableWidget`部件,并将其添加到主窗口中:
```python
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(100, 100, 400, 300)
table_widget = QTableWidget(self)
table_widget.setColumnCount(3)
table_widget.setRowCount(3)
table_widget.setHorizontalHeaderLabels(['列1', '列2', '列3'])
for row in range(3):
for col in range(3):
item = QTableWidgetItem(f'单元格({row}, {col})')
table_widget.setItem(row, col, item)
table_widget.itemClicked.connect(self.show_new_window)
self.setCentralWidget(table_widget)
```
在`TableWidget`的`itemClicked`信号连接的槽函数`show_new_window`中,我们创建一个新窗口,并显示该窗口:
```python
def show_new_window(self, item):
new_window = QWidget()
layout = QVBoxLayout(new_window)
label = QLabel(f'你点击了单元格({item.row()}, {item.column()})')
layout.addWidget(label)
new_window.show()
```
最后,我们需要创建`QApplication`对象,并运行主窗口:
```python
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
```
当运行该程序后,点击`TableWidget`中的某个单元格时,就会弹出一个新的窗口,该窗口显示了你所点击的单元格的位置信息。
这样,就实现了通过点击PyQt的TableWidget部件来触发出现新界面的功能。
阅读全文
相关推荐















