使用with pyqt4在列表视图的匹配项中获取选定项的步骤如下:
from PyQt4.QtGui import *
from PyQt4.QtCore import *
app = QApplication([])
window = QMainWindow()
layout = QVBoxLayout()
list_view = QListView()
model = QStringListModel()
data = ["Item 1", "Item 2", "Item 3"]
model.setStringList(data)
list_view.setModel(model)
layout.addWidget(list_view)
central_widget = QWidget()
central_widget.setLayout(layout)
window.setCentralWidget(central_widget)
@pyqtSlot(QModelIndex)
def get_selected_item(index):
selected_item = model.data(index, Qt.DisplayRole)
print("Selected Item:", selected_item)
activated
到槽函数get_selected_item
:list_view.activated.connect(get_selected_item)
window.show()
app.exec_()
完整的代码如下:
from PyQt4.QtGui import *
from PyQt4.QtCore import *
app = QApplication([])
window = QMainWindow()
layout = QVBoxLayout()
list_view = QListView()
model = QStringListModel()
data = ["Item 1", "Item 2", "Item 3"]
model.setStringList(data)
list_view.setModel(model)
layout.addWidget(list_view)
central_widget = QWidget()
central_widget.setLayout(layout)
window.setCentralWidget(central_widget)
@pyqtSlot(QModelIndex)
def get_selected_item(index):
selected_item = model.data(index, Qt.DisplayRole)
print("Selected Item:", selected_item)
list_view.activated.connect(get_selected_item)
window.show()
app.exec_()
使用以上代码,可以实现在列表视图的匹配项中获取选定项的功能。当用户在列表视图中选择一个项时,程序将会打印出该项的内容。你可以根据实际需求进一步处理选定项的内容。
领取专属 10元无门槛券
手把手带您无忧上云