How to scroll QListWidget to selected item

北城余情 提交于 2021-01-27 13:07:53

问题


The code below creates a single dialog window with QListWidget and QPushButton. Clicking the button fires up a scroll() function which finds and selects an "ITEM-0011".

I wonder if there is a way to scroll the list widget so the selected ITEM-0011 is at the top edge of QListWidget? Here is how the end result should look like:

from PyQt4 import QtCore, QtGui
app=QtGui.QApplication([])

def scroll():
    item = listWidget.findItems('ITEM-0011', QtCore.Qt.MatchRegExp)[0]
    item.setSelected(True)

window = QtGui.QDialog()
window.setLayout(QtGui.QVBoxLayout())
listWidget = QtGui.QListWidget()
window.layout().addWidget(listWidget)

for i in range(100):
    QtGui.QListWidgetItem('ITEM-%04d'%i, listWidget)

btn = QtGui.QPushButton('Scroll')
btn.clicked.connect(scroll)
window.layout().addWidget(btn)
window.show()
app.exec_()

回答1:


The list-widget has a scrollToItem method that will scroll an item to a specific position:

def scroll():
    item = listWidget.findItems('ITEM-0011', QtCore.Qt.MatchRegExp)[0]
    item.setSelected(True)
    listWidget.scrollToItem(item, QtGui.QAbstractItemView.PositionAtTop)


来源:https://stackoverflow.com/questions/41517945/how-to-scroll-qlistwidget-to-selected-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!