QTableView单击的信号从不发出吗?

时间:2018-10-11 07:53:26

标签: python python-3.x qtableview pyside2

我开始变得更加困惑。我无法像我想要的那样使QTableView发出其信号。我将案件减少了一些混乱,即使在那种情况下,单击时也无法发出任何信号。

例如,在该代码中,启动应用程序时,插槽“ onClickedRow”被调用了一次(我不知道为什么),但是随后我可以在任意位置点击任意数量,而该插槽从未被调用:

import sys
from PySide2 import QtWidgets, QtCore, QtGui


class Message(QtCore.QAbstractItemModel):
    def __init__(self):
        super().__init__()

        self.messageList = []

    def addMessage(self, typeName, data):
        self.messageList.append({"type": typeName,
                                 "data": data})

    def data(self, index, role):

        if not index.isValid():
            return None

        if role != QtCore.Qt.DisplayRole:
            return None

        item = self.messageList[index.row()]

        if index.column() == 0:
            return str(item["type"])
        else:
            return str(item["data"])

    def headerData(self, section, orientation, role):
        if orientation == QtCore.Qt.Horizontal:
            if role == QtCore.Qt.DisplayRole:
                if section == 0:
                    return "type"
                else:
                    return "data"

        return None

    def parent(self, index):
        if not index.isValid():
            return QtCore.QModelIndex()

        return QtCore.QModelIndex()

    def index(self, row, column, parent):
        if not self.hasIndex(row, column, parent):
            return QtCore.QModelIndex()
        else:
            return self.createIndex(row, column)

    def flags(self, index):
        if not index.isValid():
            return QtCore.Qt.NoItemFlags

        return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable

    def columnCount(self, parent):
        return 2

    def rowCount(self, parent):
        return len(self.messageList)


class FormMessageJournal(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()

        self.layout = QtWidgets.QVBoxLayout()

        self.messageTable = QtWidgets.QTableView(self)
        self.messageTable.clicked.connect(self.onClickedRow())
        self.messageList = Message()
        self.messageList.addMessage("Send", "Hello")
        self.messageList.addMessage("Send", "Hello")
        self.messageList.addMessage("Send", "Hello")
        self.messageList.addMessage("Send", "Hello")
        self.messageTable.setModel(self.messageList)
        self.layout.addWidget(self.messageTable)

        self.setLayout(self.layout)

    def onClickedRow(self, index=None):
        print("Click !")


if __name__ == "__main__":
    app = QtWidgets.QApplication([])

    widget = FormMessageJournal()
    widget.show()

    sys.exit(app.exec_())

我是唯一遇到这类问题的人吗?

1 个答案:

答案 0 :(得分:1)

self.messageTable.clicked.connect(self.onClickedRow())

更改为:

self.messageTable.clicked.connect(self.onClickedRow)