[英]PyQt: How to scroll to right in a QListWidget?
在 PyQt QListWidget 中,我使用完整路徑拖放文件。 現在我希望滾動條在每次拖動某些東西時向右滾動。但是,似乎只有scrollToTop()
和scrollToBottom()
,但我找不到scrollToLeft()
或scrollToRight()
或類似的東西。 列表項文本的右 alignment 沒有幫助,顯然我需要向右滾動水平滾動條。
如何自動向右滾動,以便我看到文件名,而不是路徑的開頭? 它必須是一個簡單的設置,但到目前為止我還沒有找到有用的文檔或示例。
代碼:
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())
您甚至可以為所有項目視圖提供“猴子補丁”function,方法是將其放在導入 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()
並不總是足夠的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.