目的是每当用户单击列表中的项目时检测项目索引。
示例:
A
B
C
D
E
如果用户单击C,那么我想从list()
中检索该索引号。
试图直接打印出item变量,但我在命令提示符下得到了以下输出:
[<PyQt5.QtCore.QModelIndex object at 0x0416CA70>]
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5 import QtWidgets, QtGui, QtCore
from PyQt5.QtGui import QBrush, QColor
class Widget(QtWidgets.QWidget):
def __init__(self):
super().__init__()
lay = QtWidgets.QVBoxLayout(self)
self.listView = QtWidgets.QListView()
self.label = QtWidgets.QLabel("Please Select item in the QListView")
lay.addWidget(self.listView)
lay.addWidget(self.label)
model = QStringListModel()
textList = list()
textList = ["Itemname1", "Itemname2", "Itemname3", "Itemname4", "Itemname5", "Itemname6", "Itemname7", "Itemname8"]
model.setStringList(textList)
self.listView.setModel(model)
self.listView.clicked[QtCore.QModelIndex].connect(self.on_clicked)
def on_clicked(self, index):
item = self.listView.selectedIndexes()
print(item)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
输出为[<PyQt5.QtCore.QModelIndex object at 0x0416CA70>]
,但我想要整数。
答案 0 :(得分:0)
此便捷功能将返回所有已选择和 视图中的非隐藏项目索引。该列表没有重复项, 并且未排序。
返回QModelIndex的列表。以下将获得第一个索引:
import os
import requests
from concurrent import futures
def fetch(url, session = None):
if session:
r = session.get(url, timeout = 60.)
else:
r = reqests.get(url, timeout = 60.)
r.raise_for_status()
return r.content
def fetch_all(urls, session = requests.session(), threads = 8):
with futures.ThreadPoolExecutor(max_workers = threads) as executor:
future_to_url = {executor.submit(fetch, url, session = session): url for url in urls}
for future in futures.as_completed(future_to_url):
url = future_to_url[future]
if future.exception() is None:
yield url, future.result()
else:
print(f"{url} generated an exception: {future.exception()}")
yield url, None
def get_urls(search_term, number_images = 10, token = "", session = requests.session()):
r = requests.get(f"https://pixabay.com/api/?key={token}&q={search_term}&per_page={number_images}")
r.raise_for_status()
urls = [hit["webformatURL"] for hit in r.json().get("hits", [])]
return urls
if __name__ == "__main__":
root_dir = os.getcwd()
session = requests.session()
urls = get_urls("term", token = "token", session = session)
for url, content in fetch_all(urls, session = session):
if content is not None:
f_dir = os.path.join(root_dir, "images")
if not os.path.isdir(f_dir):
os.makedirs(f_dir)
with open(os.path.join(f_dir, os.path.basename(url)), "wb") as f:
f.write(content)
此外,对于单个选择,您可以改用print(item[0].row())