from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QStandardItemModel, QStandardItem
from PyQt5.QtCore import Qt
from PyQt5 import QtCore, QtWidgets
def selected_tb_text(table_view):
try:
indexes = table_view.selectedIndexes()
indexes_dict = {}
for index in indexes:
row, column = index.row(), index.column()
if row in indexes_dict.keys():
indexes_dict[row].append(column)
else:
indexes_dict[row] = [column]
text = ''
for row, columns in indexes_dict.items():
row_data = ''
for column in columns:
data = table_view.model().item(row, column).text()
if row_data:
row_data = row_data + '\t' + data
else:
row_data = data
if text:
text = text + '\n' + row_data
else:
text = row_data
return text
except BaseException as e:
print(e)
return ''
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
self.tableView = QtWidgets.QTableView(Form)
self.tableView.setEnabled(True)
self.tableView.setGeometry(QtCore.QRect(5, 5, 400, 200))
self.tableView.setObjectName("tableView")
QtCore.QMetaObject.connectSlotsByName(Form)
class StartRun(QWidget, Ui_Form):
def __init__(self):
super().__init__()
self.init_ui()
self.show()
def init_ui(self):
self.setupUi(self)
self.update_table_view()
def update_table_view(self):
data = [
(1, '張三', 18),
(2, '李四', 29),
(3, '王五', 25),
(4, '趙六', 26),
]
columns = ['id', 'name', 'age']
model = QStandardItemModel(len(data), len(columns))
model.setHorizontalHeaderLabels([str(i) for i in columns])
for row in range(len(data)):
for column in range(len(data[row])):
item = QStandardItem(str(data[row][column]))
model.setItem(row, column, item)
self.tableView.setModel(model)
def keyPressEvent(self, event):
if (event.key() == Qt.Key_C) and QApplication.keyboardModifiers() == Qt.ControlModifier:
text = selected_tb_text(self.tableView)
if text:
try:
clipboard = QApplication.clipboard()
clipboard.setText(text)
except BaseException as e:
print(e)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
S = StartRun()
sys.exit(app.exec_())
本作品採用《CC 協議》,轉載必須註明作者和本文連結