Search code examples
pythonqtpysidecopy-pasteqtableview

Disallow copy/paste in QTableView in pyside


I have QTableView that gets information from a QSqlQueryModel and displays it in real time. The thing is, QTableView allows the user to copy and paste the info from one of the fields.

    projectModel = QtSql.QSqlQueryModel()
    projectModel.setQuery("select * from queue",self.db)
    self.total_rows = projectModel.rowCount()
    projectModel.setHeaderData(0, QtCore.Qt.Horizontal, 'ID cola')
    projectModel.setHeaderData(1, QtCore.Qt.Horizontal, 'Código')

    self.projectView = QtGui.QTableView()
    self.projectView.setModel(projectModel)
    self.projectView.resizeColumnsToContents()
    self.projectView.horizontalHeader().setStretchLastSection(True)

How do I deny copying the content of QTableView and pasting it outside in a text editor, for example?


Solution

  • You can make the whole table read-only like this:

        self.projectView.setEditTriggers(QAbstractItemView.NoEditTriggers)
    

    EDIT:

    If you also want to prevent copying of cells, you will need to kill the relevant keyboard shortcuts. Below is some example code that does that:

    from PySide import QtGui, QtCore
    
    class Window(QtGui.QWidget):
        def __init__(self, rows, columns):
            super(Window, self).__init__()
            self.table = QtGui.QTableView(self)
            model =  QtGui.QStandardItemModel(rows, columns, self.table)
            for row in range(rows):
                for column in range(columns):
                    item = QtGui.QStandardItem('(%d, %d)' % (row, column))
                    model.setItem(row, column, item)
            self.table.setModel(model)
            self.table.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
            layout = QtGui.QVBoxLayout(self)
            layout.addWidget(self.table)
            self.table.installEventFilter(self)
    
        def eventFilter(self, source, event):
            if (source is self.table and
                event.type() == QtCore.QEvent.KeyPress and
                event == QtGui.QKeySequence.Copy):
                return True
            return super(Window, self).eventFilter(source, event)
    
    if __name__ == '__main__':
    
        import sys
        app = QtGui.QApplication(sys.argv)
        window = Window(5, 5)
        window.setGeometry(600, 300, 600, 250)
        window.show()
        sys.exit(app.exec_())