I have multiple QTableWidget in my application:
I want to be able to copy the text stored in a cell when selected either by pressing ctrl+c or by right-clicking on it and clicking on a 'copy' menu.
The tables I am using are costumized, and this is the code that implements em:
class AlphaPiQTableWidget(QTableWidget):
def __init__(self, attr_dict):
super(AlphaPiQTableWidget, self).__init__()
values = list(attr_dict.values())
attributes = list(attr_dict.keys())
# Tabella che mostra i valori del competitor
self.setRowCount(len(attributes))
self.setColumnCount(2)
self.setCellWidget(0,0, QLabel(attributes[0]))
self.setCellWidget(1,0, QLabel(attributes[1]))
self.setCellWidget(2,0, QLabel(attributes[2]))
self.setCellWidget(3,0, QLabel(attributes[3]))
self.setCellWidget(0,1, QLabel(str(values[0])))
self.setCellWidget(1,1, QLabel(str(values[1])))
self.setCellWidget(2,1, QLabel(str(values[2])))
self.setCellWidget(3,1, QLabel(str(values[3])))
self.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.customContextMenuRequested.connect(self.showTableMenu)
# Fai occupare tutto lo spazio libero nel layout alla tabella
h_header = self.horizontalHeader()
h_header.setSectionResizeMode(QtWidgets.QHeaderView.Stretch)
h_header.setVisible(False)
v_header = self.verticalHeader()
v_header.setSectionResizeMode(QtWidgets.QHeaderView.Stretch)
v_header.setVisible(False)
# Fai in modo che la tabella sia sempre visualizzata per intero
self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
def showTableMenu(self, pos):
# get the text of the index at the mouse cursor (if any)
text = self.indexAt(pos).data()
menu = QtWidgets.QMenu()
copyAction = menu.addAction('Copy')
if not text:
copyAction.setEnabled(False)
# show the menu
res = menu.exec_(QtGui.QCursor.pos())
if res == copyAction:
# if the menu has been triggered by the action, copy to the clipboard
QtWidgets.QApplication.clipboard().setText(text)
The issue is that when I copy the text by right-clicking on a cell and pressing on 'copy' self.indexAt(pos).data()
always returns None
. Why is that?
P.S. all the AlphaPiQTableWidget
are stored on a QHBoxLayout along with other widgets (such as labes and buttons as you can see.
That there are cells does not imply that there are items, in your case you have placed widgets on top of the cells, so in reality you want to get the text of those QLabels.
The first thing is to obtain the QLabel using the cellWidget method, but for this it is necessary to obtain the row and column of the pressed cell, in which case the indexAt() method must be used:
def showTableMenu(self, pos):
index = self.indexAt(pos)
label = self.cellWidget(index.row(), index.column())
text = label.text()
# ...
Another solution is not to use QLabels but rather QTableWidgetItem:
self.setItem(0,0, QTableWidgetItem(attributes[0]))
# ...