【问题标题】:PyQt4 Selected Item Text in QTableView delayed by one click一键延迟QTableView中的PyQt4 Selected Item Text
【发布时间】:2023-12-29 08:00:01
【问题描述】:

我使用QTableView 显示QSqlTableModel 的内容,同时使用QSortFilterProxyModel 过滤记录。在下面的代码中,我设法在用户单击单元格时显示选定的文本(无论是否应用了过滤器)。但是,它总是落后 1 次单击,开始后的第一次单击会导致 IndexError: pop from empty list 并且当在同一行中选择新列时没有任何反应。

我在初始化表后尝试选择索引,似乎没有做任何事情。我不知道下一步该尝试什么?

class TableViewer(QtGui.QWidget):

    self.model =  QSqlTableModel()
    self._proxyModel = QtGui.QSortFilterProxyModel()
    self._proxyModel.setSourceModel(self.model)

    self.tv= QTableView()
    self.tv.setModel(self._proxyModel)

   '''Call-able filter - pass in string to filter everything that doesn't match string'''
    QtCore.QObject.connect(self.textEditFilterBox,  QtCore.SIGNAL("textChanged(QString)"),     self._proxyModel.setFilterRegExp)


     def getItem(self):
         '''Retruns item text of selected item'''
         index = self.selectionModel.selectedIndexes().pop()
         if index.isValid():
             row = index.row()
             column = index.column()
             model = index.model()
             if hasattr(model, 'mapToSource'):
                 #proxy model
                 modelIndex = model.mapToSource(index)
                 print (modelIndex.row(), modelIndex.column())
                 return self.model.record(modelIndex.row()).field(modelIndex.column()).value().toString()
         return self.model.record(row).field(column).value().toString()

class MainWindow(QtGui.QMainWindow):

    #initialize TableViewer

    self.tblViewer.connect(self.tblViewer.tv.selectionModel(),
            SIGNAL(("currentRowChanged(QModelIndex,QModelIndex)")),
            self.tblItemChanged)

    def tblItemChanged(self, index):
        '''display text of selected item '''
        text = self.tblViewer.getItem()
        print(text)

【问题讨论】:

    标签: python database pyqt4 qtableview qsqltablemodel


    【解决方案1】:

    当在同一行中选择新列时,什么也不会发生。

    那是因为您使用的是currentRowChanged 信号。如果您选择同一行中的列,则不会触发该信号。您应该使用currentChanged 信号。 (而且,你应该使用new style connections

    而且,如果您只追求数据,则不需要那些东西来获取非代理QModelIndex 然后询问模型等。QModelIndex 有一个方便的方法.data 即只是为了这个目的。此外,信号会向您发送选定的索引,您不需要额外的工作。这使您的代码变得如此简单:(注意:不需要getItem 方法)

    class MainWindow(QtGui.QMainWindow):
        def __init__(self, parent=None):
            #initialize TableViewer
            self.tblViewer.tv.selectionModel().currentChanged.connect(self.tblItemChanged)
    
        def tblItemChanged(self, current, previous):
            '''display text of selected item '''
            # `data` defaults to DisplayRole, e.g. the text that is displayed
            print(current.data().toString()) 
    

    【讨论】:

    • 简单得多,而且效果很好,谢谢。 (我不知道新样式,它看起来更干净再次感谢。)
    最近更新 更多