I have a widget which can contain one or more QTableView child widgets. By default, when I select a range in one of QTableViews and hit crtl+c only the leftmost uppermost cell gets copied to the clipboard. I would like to copy the entire range, so I implemented a copy() slot which does the job. I would like the copy slot to be accessible both from a context menu (when the user makes a selection and right clics the corresponding QTableView) and by the ctrl+c shortcut.
class Widget
{
Q_OBJECT
public:
void setupContextMenu();
private:
QMenu* contextMenu_;
QAction* copyAction_;
QTableView* tableView_;
private slots:
void copy();
}
void Widget::setupContextMenu()
{
contextMenu_ = new QMenu(this);
copyAction_ = contextMenu_->addAction("&Copy");
copyAction_->setShortcut(QKeySequence::Copy);
connect(copyAction_, SIGNAL(triggered()),
this, SLOT(copy()));
}
When I select a range and right click, the appropriate context menu pops up and it even contains the name of the shortcut. When I click the “Copy” action in the context menu, the copy() slot gets executed. However the ctrl+c shortcut just copies only the leftmost uppermost cell in the selection as before. Also, the copy() slot does not get executed.
How can I repair this?
I am not sure but maybe shortcut key doesn’t work with contextual menus in Qt?
The handling of copy shortcut happens in
QAbstractItemView::keyPressEvent(). You can install an event filter to your QTableView watching forKeyPressevent and handle your copy there.