Search code examples
c++qtqt5qtreeview

How to disable the default copy behavior in QTreeView?


I have a QTreeView with a QStandardItemModel and I would like to be able to prevent the user from copying the text of the items.

#include <QMainWindow>
#include <QStandardItemModel>
#include <QTreeView>

class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    explicit MainWindow(QWidget *parent = nullptr) :
        QMainWindow(parent)
    {
        auto *treeView = new QTreeView(this);
        auto *model = new QStandardItemModel(this);

        for (int n = 0; n < 5; n++)
            model->appendRow(createItem(QString::number(n)));

        treeView->setModel(model);
        treeView->setContextMenuPolicy(Qt::NoContextMenu);

        setCentralWidget(treeView);
    }

private:
    QStandardItem *createItem(const QString &name)
    {
        auto *item = new QStandardItem(name);

        item->setFlags(Qt::ItemIsEnabled);

        return item;
    }
};

I have already made the items not editable and disabled the context menu. However, it is still possible for the user to click on an item and copy the text by pressing Ctrl+C. I can use Qt::NoItemFlags, but I want the items to be enabled.

How to accomplish that?


Solution

  • To disable the default copy behavior of QTreeView reimplement QTreeView::keyPressEvent in a subclass, e.g. TreeView, like that:

    void TreeView::keyPressEvent(QKeyEvent *event)
    {
        if (!(event == QKeySequence::Copy))
            QTreeView::keyPressEvent(event);
    }
    

    Then in your code instead of QTreeView:

    auto *treeView = new QTreeView(this);
    

    instantiate TreeView:

    auto *treeView = new TreeView(this);