Pedro Witzel
Pedro Witzel

Reputation: 370

Overwrite Copy Text operation from a QTreeWidget

I have a QTreeWidget where I would to overwrite the Copy Text (ctrl+c) from the QTreeWidgetItem.

The default behaviour is to copy the text from the selected column, but I'd like to update the values with more information that I have on the background.

Is there a native way of doing it without capturing the ctrl+c with a keyPressEvent ?

Upvotes: 0

Views: 1135

Answers (1)

vahancho
vahancho

Reputation: 21230

You can try the following approach to store your own stuff in clipboard without overriding QWidget::keyPressEvent():

// Assuming tree widget already exists.
auto shortcut = new QShortcut(QKeySequence("Ctrl+C"), treeWidget);
QObject::connect(shortcut, &QShortcut::activated, [treeWidget] () {
    auto selected = treeWidget->selectedItems();
    // Get only first selected item's text.
    if (selected.size() > 0)
    {
        QClipboard *clipboard = QApplication::clipboard();
        clipboard->setText(QString("Custom clipboard text: %1").arg(selected.at(0)->text(0)));
    }
});

In the code I used QShortcut to handle Ctrl+C key sequence and store selected tree widget item's text (customized) into the clipboard.

Upvotes: 2

Related Questions