Search code examples
pythonpyqtpyqt5qtablewidget

I want just the first column to be clickable in QTableWidget using pyqt5


I have QTableWidget with 2 columns. I want just the first column clickable or selectable, other column should not be.

In below example, I just want Session Column to be clickable, not the Archive Object Column

enter image description here

def _populateJobTW(self):
    #Populating ListWidget with data
    myDate = self.RundateEdit.date()
    SearchDate=myDate.toString('MM/dd/yyyy')
    mycursor=mydbhdb.cursor()
    mycursor.execute("""select "Archiving Session", "Archiving Object"||'('||"Variant"||')' from admirun where
     "Date of Archiving" = '{}' and "Archiving Object" != 'BC_XMB';""".format(SearchDate))
    result=mycursor.fetchall()
    self.JobTW.setRowCount(0)

   for row_number, row_data in enumerate(result):
        self.JobTW.insertRow(row_number)
        for column_number, data in enumerate(row_data):
            #item = self.cell("text")
            #item.setFlags(QtCore.Qt.ItemIsEnabled)
            self.JobTW.setItem(row_number, column_number, QTableWidgetItem(str(data)))
            ##############Make all column un selectable or other than the first column
            if column_number > 0:
                print(column_number)
                data1 = QTableWidgetItem(data)
                print(data1.text())
                data1.setFlags(data1.flags() | Qt.ItemIsSelectable)
                #data.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
def _cellClicked(self, row, col): 
    # Row and Col came directly from the click 
    item = self.JobTW.item(row, col) # Will assign the values 
    print("The session Nnumber is {} ".format(item.text()))

Solution

  • A possible solution to prevent the clicked signal from being emitted for certain items may be to override the mouseXEvents method overriding the default behavior but that can cause problems, instead a trivial solution is to filter in the slot:

    def _cellClicked(self, row, column): 
        # Row and Col came directly from the click 
        if column == 0:
            item = self.JobTW.item(row, col) # Will assign the values 
            if item is not None:
                print("The session Nnumber is {} ".format(item.text()))
    

    With the above, the columns are still selected, and if you do not want that behavior, you can use a delegate:

    class NonSelectableDelegate(QStyledItemDelegate):
        def editorEvent(self, event, model, option, index):
            return index.column() != 0
    
    delegate = NonSelectableDelegate(self.JobTW)
    self.JobTW.setItemDelegate(delegate)