如何解决PyQt:如何在 QListWidget 中向右滚动?
在 PyQt QListWidget 中,我拖放文件及其完整路径。现在我希望滚动条在每次拖动时向右滚动。
但是,似乎只有 scrollToTop()
和 scrollToBottom()
,但我找不到 scrollToLeft()
或 scrollToRight()
或任何类似的东西。列表项文本的右对齐无济于事,显然我需要向右滚动水平滚动条。
如何自动向右滚动,以便我看到文件名,不是路径的开头? 这一定是一个简单的设置,但到目前为止我还没有找到有用的文档或示例。
代码:
import sys
from PyQt5.QtGui import *
from PyQt5.QtWidgets import QListWidget,QListWidgetItem,QApplication,QWidget,QAbstractItemView,QVBoxLayout
class MyListWidget(QListWidget):
def __init__(self,parent):
super(MyListWidget,self).__init__(parent)
# self.setDragDropMode(QAbstractItemView.InternalMove)
self.setAcceptDrops(True)
def dragenterEvent(self,event):
if event.mimeData().hasUrls() or event.mimeData().hasFormat("text/plain"):
event.acceptProposedAction()
else:
super(MyListWidget,self).dragenterEvent(event)
def dropEvent(self,event):
if event.mimeData().hasUrls():
for url in event.mimeData().urls():
item = QListWidgetItem(url.toLocalFile())
self.addItem(item)
event.acceptProposedAction()
elif event.mimeData().hasFormat("text/plain"):
self.addItem(event.mimeData().text())
else:
super(myListWidget,self).dropEvent(event)
self.scrollToBottom() ### but I want scrollToRight() !!!
class MyWindow(QWidget):
def __init__(self):
super().__init__()
self.left = 50
self.top = 50
self.width = 900
self.height = 500
self.initUI()
def initUI(self):
self.vBox = QVBoxLayout()
self.lw_myList = MyListWidget(self)
self.vBox.addWidget(self.lw_myList)
self.setLayout(self.vBox)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
# app.setStyle("plastique")
window = MyWindow()
# window.show()
sys.exit(app.exec_())
结果:
解决方法
从 QAbstractScrollArea 继承的所有小部件的编程滚动可以通过设置其滚动条的值(即使它们不可见)来实现(并且应该只完成)。
因为像 QListWidget(从 QListView 和 QAbstractItemView 继承)这样的项目视图需要一些时间来正确地布置新项目,所以通常首选调用 QCoreApplication.processEvents()
并且,只是为了安全,updateGeometries()
:
def dropEvent(self,event):
# ...
# ensure that the event queue is correctly processed,which includes
# laying out new items
QApplication.processEvents()
# ensure that the geometry of child widgets is correctly updated too
self.updateGeometries()
# finally,set the horizontal scroll bar to its maximum
self.horizontalScrollBar().setValue(self.horizontalScrollBar().maximum())
您甚至可以通过将其放在导入 QtWidgets 的第一个脚本的开头,为所有项目视图提供“猴子补丁”功能:
def itemViewScrollToRight(self):
QApplication.processEvents()
self.updateGeometries()
self.horizontalScrollBar().setValue(
self.horizontalScrollBar().maximum())
QAbstractItemView.scrollToRight = itemViewScrollToRight
# ...
def dropEvent(self,event):
# ...
self.scrollToRight()
PS:请注意,您应该始终实现 dragMoveEvent()
并接受自定义拖动实现的事件,因为 dragEnterEvent()
并不总是足够的。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。