我只想使用 pyqt5 在 QTableWidget 中点击第一列

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

我有 2 列的 QTableWidget。我只希望第一列可点击或可选择,其他列不应该。

在下面的示例中,我只希望会话列可点击,而不是存档对象列

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()))

防止某些项目发出点击信号的可能解决方案可能是覆盖覆盖默认行为的 mouseXEvents 方法,但这可能会导致问题,而不是一个简单的解决方案是在插槽中进行过滤:

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()))

在上面的情况下,列仍然处于选中状态,如果您不希望出现这种情况,可以使用委托:

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