QTreeView数据更改了信号/插槽的实现?

时间:2019-06-14 18:31:44

标签: python pyqt pyqt5 python-3.7 qtreeview

我正在使用pyqt5 / python 3.7 / win10,并且我有一个QTreeView,它只有一个可编辑的列,可以很好地对其进行编辑。我现在需要做的就是告诉程序该字段是否已更改(或检查是否已更改),无论是按下回车键还是Enter键,或者该字段由于鼠标单击其他任何地方而失去焦点。

我提供了一个简单的程序,它可以反映我到目前为止的所有情况,并且选择了单击字段而不是双击来选择要编辑的字段。

我花了很多时间试图解决这个问题,尽管我看到了可能的答案,但我还没有找到一个可以解决的办法。我敢肯定这可能很简单,但是我在实施该解决方案方面花费了很多时间。

from sys import exit as sysExit

from PyQt5.QtCore import *
from PyQt5.QtGui  import *
from PyQt5.QtWidgets import *

class CustomItemModel(QStandardItemModel):
    def headerData(self, section, orientation, role):
        if role == Qt.ForegroundRole:
            brush = QBrush()
            brush.setColor(Qt.blue)
            brush.setStyle(Qt.SolidPattern)
            return brush

        elif role == Qt.BackgroundRole:
            brush = QBrush()
            brush.setColor(Qt.yellow)
            brush.setStyle(Qt.SolidPattern)
            return brush

        elif role == Qt.FontRole:
            font = QFont()
            font.setBold(True)
            font.setPointSize(10)
            return font

        return super().headerData(section, orientation, role)

class ItemDsplyr(QTreeView):
    def __init__(self, CentrPane):
        QTreeView.__init__(self, CentrPane)
        self.CntrPane = CentrPane
        self.setEditTriggers(QTreeView().NoEditTriggers)
        self.model = CustomItemModel(0, 4)

        self.model.setHorizontalHeaderLabels(['', 'ItemName', 'Value', 'Units'])
        self.model.setHeaderData(2, Qt.Horizontal, Qt.AlignCenter, Qt.TextAlignmentRole)
        self.setModel(self.model)

        self.setColumnWidth(0, 1)  #Not sure what the minimum column width is but is greater than 1
        self.setColumnHidden(0, True)

        self.header().setSectionResizeMode(0, QHeaderView.Fixed)

        self.header().setStretchLastSection(False)
        self.header().setSectionResizeMode(1, QHeaderView.Stretch)
        self.setColumnWidth(2, 75)
        self.setColumnWidth(3, 100)

        self.clicked.connect(self.__itemSingleClicked)

    @property
    def CntrPane(self):
        return self.__parent

    @CntrPane.setter
    def CntrPane(self, value):
        self.__parent = value

    def SetContent(self, tmpItmList):
        self.model.setRowCount(0)

        for Item in tmpItmList:
            blnkVal = QStandardItem('')

            ItmNam = QStandardItem(Item['ItemName'])
            ItmNam.setTextAlignment(Qt.AlignLeft)
            ItmNam.isEditable = False

            ItmVal = QStandardItem(Item['Value'])
            ItmVal.setTextAlignment(Qt.AlignCenter)

            ItmUnt = QStandardItem((Item['Units']))
            ItmUnt.setTextAlignment(Qt.AlignLeft)
            ItmUnt.isEditable = False

            self.model.appendRow([blnkVal, ItmNam, ItmVal, ItmUnt])

    def __itemSingleClicked(self, index):
        Item = self.selectedIndexes()[0]
        CurRow = index.row()
        ItemIdx = index.sibling(CurRow, 1)
        ValuIdx = index.sibling(CurRow, 2)
        self.edit(ValuIdx)

        ItemVal = Item.model().itemFromIndex(ItemIdx).text()
        ValuVal = Item.model().itemFromIndex(ValuIdx).text()
        self.CntrPane.CurItemValue(ItemVal, ValuVal)

class CenterPanel(QWidget):
    def __init__(self, MainWin):
        QWidget.__init__(self)

        self.MainWin = MainWin
        self.ListItm = ''
        self.ListVal = ''

        ItmList = [
            {'ItemName':'Cal-Itm-1', 'Value':'54',  'Units':'Units'},
            {'ItemName':'Cal-Itm-2', 'Value':'54',  'Units':'Units'},
            {'ItemName':'Cal-Itm-1', 'Value':'10',  'Units':'Passes'},
            {'ItemName':'Cal-Itm-2', 'Value':'2.5', 'Units':'Volts'},
            {'ItemName':'Run-Itm-1', 'Value':'2',   'Units':'Units'},
            {'ItemName':'Run-Itm-2', 'Value':'1',   'Units':'Units'},
            {'ItemName':'Run-Itm-1', 'Value':'10',  'Units':'Units'},
            {'ItemName':'Run-Itm-2', 'Value':'50',  'Units':'Units'},
            {'ItemName':'Tbl-Itm-1', 'Value':'0',   'Units':'Units'},
            {'ItemName':'Tbl-Itm-2', 'Value':'0',   'Units':'Units'},
            {'ItemName':'Tbl-Itm-1', 'Value':'0',   'Units':'Units'},
            {'ItemName':'Tbl-Itm-2', 'Value':'255', 'Units':'Units'}
            ]

        self.CatGrpTree = QTextEdit()

        self.ItemDsply = ItemDsplyr(self)
        self.ItemDsply.SetContent(ItmList)

        CntrPane = QSplitter(Qt.Horizontal, self)
        CntrPane.addWidget(self.CatGrpTree)
        CntrPane.addWidget(self.ItemDsply)
        CntrPane.setSizes([50,200])

        hbox = QHBoxLayout(self)
        hbox.addWidget(CntrPane)

        self.setLayout(hbox)

    @property
    def MainWin(self):
        return self.__parent

    @MainWin.setter
    def MainWin(self, value):
        self.__parent = value

    def CurItemValue(self, LstItm, LstVal):
        print("List Item/Value Clicked:",LstItm,"/",LstVal)
        if LstItm != self.ListItm:
            self.ListItm = LstItm
            self.ListVal = LstVal

class Window(QMainWindow):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        self.title = 'Main Window'
        self.left = 100
        self.ztop = 100
        self.wide = 700
        self.high = 600

        self.InitGUI()

    def InitGUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.ztop, self.wide, self.high)

        self.CenterPane = CenterPanel(self)
        self.setCentralWidget(self.CenterPane)

        self.setStyle(QStyleFactory.create('Cleanlooks'))

if __name__ == "__main__":
    MainApp = QApplication([])
    # This fixes a display issue with Windows
    MainApp.setStyle("fusion")

    MainGUI = Window()
    MainGUI.show()

    sysExit(MainApp.exec_())

可以看出(运行此命令时),您会得到一个QTreeView(主要是一个List,但从我的研究来看,最好使用QTreeView)。如果单击一行,您将立即进入“值”列中的编辑模式。但是,我无法确定如何知道何时检查字段是否已更改(我正在捕获预编辑的值)。因此,仅以“丢失焦点”为准,而“数据更改”会更好。

1 个答案:

答案 0 :(得分:2)

如果您想获得仅更改的项目文本,则必须使用dataChanged(...)信号

# ...
class ItemDsplyr(QTreeView):
    def __init__(self, CentrPane):
        QTreeView.__init__(self, CentrPane)
        # ...
        self.model.setHeaderData(2, Qt.Horizontal, Qt.AlignCenter, Qt.TextAlignmentRole)
        self.model.dataChanged.connect(self.on_data_changed)
        # ...

    @pyqtSlot("QModelIndex", "QModelIndex", "QVector<int>")
    def on_data_changed(self, top_left, bottom_right, roles):
        if top_left == bottom_right and Qt.DisplayRole in roles:
            print(top_left.data())
# ...