【发布时间】:2020-07-15 23:40:27
【问题描述】:
我正在使用 PyQt5 制作应用程序并遇到一些麻烦。我想通过按 Enter 键从 QTableView 中选择数据并将其显示在 QLineEdit 中。我已经用 doubleClicked 信号完成了这些事情,但我仍然想通过两种方式向 QLineEdit 显示数据,然后在按下 Enter 键或双击后立即关闭 QTableView 对话框。 这是我的代码:
import sys
import os
from PyQt5 import QtCore, QtGui, QtWidgets, uic
class Application(QtWidgets.QMainWindow):
def __init__(self):
super(Application, self).__init__()
self.mainwindow = uic.loadUi('test.ui', self)
self.mainwindow.pushButton.clicked.connect(self.table)
def table(self):
self.table = QtWidgets.QTableView()
data = [
[2, 3, 5],
[23, 4, 5],
[2, 6, 7],
[0, 3, 5]
]
self.model = TableModel(data)
self.table.setModel(self.model)
self.table.doubleClicked.connect(self.on_click)
self.table.show()
def on_click(self, signal):
row = signal.row() # RETRIEVES ROW OF CELL THAT WAS DOUBLE CLICKED
column = signal.column() # RETRIEVES COLUMN OF CELL THAT WAS DOUBLE CLICKED
cell_dict = self.model.itemData(signal) # RETURNS DICT VALUE OF SIGNAL
cell_value = cell_dict.get(0) # RETRIEVE VALUE FROM DICT
index = signal.sibling(row, 0)
index_dict = self.model.itemData(index)
index_value = index_dict.get(0)
print(
'Row {}, Column {} clicked - value: {}\n'.format(row, column, cell_value))
self.mainwindow.lineEdit.setText('%s' %cell_value)
class TableModel(QtCore.QAbstractTableModel):
def __init__(self, data):
super(TableModel, self).__init__()
self._data = data
def data(self, index, role):
if role == QtCore.Qt.DisplayRole:
return self._data[index.row()][index.column()]
def rowCount(self, index):
return len(self._data)
def columnCount(self, index):
return len(self._data[0])
if __name__ == '__main__':
application = QtWidgets.QApplication(sys.argv)
window = Application()
window.show()
application.exec_()
还有我的桂:
让我解释一下:当点击按钮时,它会显示一个数据表,然后我想通过按回车键选择表中的数据,然后它将数据显示到 QlineEdit 并关闭表
【问题讨论】:
-
为了帮助您解决问题,您需要提供您正在使用的 UI,否则您的 MRE 不是 MRE,因为它不会运行。
标签: python pyqt pyqt5 qtableview