我需要一个带有QComboBox
按钮的QListView
,但是因为编写委托(delegate)是一个巨大的痛苦。我选择了 QTableView,因为每行总是有相同的按钮。我唯一的问题是我似乎无法从 QComboBox
中捕捉到 clicked
信号。
我附上了一个 mwe 来说明我的意思:
from PyQt5.QtCore import QModelIndex, Qt, QAbstractTableModel, QVariant
from PyQt5.QtWidgets import QApplication, QComboBox, QTableView, QWidget, QVBoxLayout
class Model(QAbstractTableModel):
def data(self, index, role=Qt.DisplayRole):
if role == Qt.DisplayRole:
col = index.column()
if col == 0:
return str(index.row())
elif col == 1:
return '✎'
elif col == 2:
return '✘'
return QVariant()
def columnCount(self, parent=QModelIndex()):
return 3
def rowCount(self, parent=QModelIndex()):
return 5
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
model = Model()
main = QWidget()
layout = QVBoxLayout(main)
view = QTableView()
view.clicked.connect(lambda _: print('Click Table')) # Works fine
view.setModel(model)
layout.addWidget(view)
combo = QComboBox()
combo.setModel(model)
combo.setView(QTableView())
combo.view().clicked.connect(lambda _: print('Click Combo')) # Does'nt show
layout.addWidget(combo)
main.resize(500, 300)
main.show()
sys.exit(app.exec_())
最佳答案
您可以使用以下信号来触发组合框中的点击:
view = QTableView()
view.clicked.connect(lambda: print('Click Table')) # Works fine
view.setModel(model)
layout.addWidget(view)
combo = QComboBox()
combo.setModel(Model())
combo.setView(QTableView())
combo.activated.connect(lambda: print('Click Combo')) # Works fine too
layout.addWidget(combo)
或者,如果您只需要检测单击或键盘输入何时更改所选项目:
combo.currentIndexChanged.connect(lambda: print('Click Combo'))
关于python - QTableView 中的单击信号,它是 QComboBox 的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45576179/