The Qt desktop app I'm writing contains a QCombobox in the UI (made with Designer). After I select the QCombobox, I can change the selected item by scrolling the mouse wheel, or by pressing the up/down arrows on the keyboard. That all works fine.
When navigating using the keyboard down arrow, for example, when I reach the bottom item in the list, the down arrow no longer changes the selected item. I understand that this is the expected behavior.
But for this particular QComboBox I'd like to be able to keep pressing the down arrow after reaching the final item in the list, and "wrap" back to the first item, so I can continue to cycle through the items. I have studied the documentation for QComboBox at https://doc.qt.io/qt-5/qcombobox.html and for QAbstractItemModel at https://doc.qt.io/qt-5/qabstractitemmodel.html, but I could not discover any way to achieve what I want here.
Ideally I'd prefer a solution that works for keyboard arrow navigation, for mouse scroll wheel navigation, and for any other UI gesture that might try to activate the "next" or "previous" item in the QComboBox.
I didn't try this solution, but I'm guessing that it's right by intuition.
I think you need to do:
Override keyPressEvent(QKeyEvent *e) to detect up and down arrows.
If the down arrow is pressed, check if it's the last index using currentIndex() const function, compared to the size of the combo box itself.
If so, change the current index to the first one using setCurrentIndex(int index).
Do the same for up arrow if you reached the first index.
P.S. As currentIndex() returned the index after pressing, this might make it jump from the penultimate index to the first one. Thus, I suggest using a private boolean member to be toggled when the condition is met for the first time.
I hope this solution helps you.
The full solution to this problem has a few different aspects.
When the QComboBox is expanded to show all the items, an elegant semantic solution is to override the QAbstractItemView::moveCursor() method. This part of the solution does not require low level event handlers because moveCursor() encapsulates the concept of "next" and "previous". Sadly this only works when the QComboBox is expanded. Note that the items are not actually activated during navigation in this case, until another gesture like a click or enter occurs.
When the QComboBox is collapsed to show one item at a time (the usual case), we have to resort to the low level approach of capturing each relevant gesture, as sketched in the answer by Mohammed Deifallah. I wish Qt had a similar abstraction here analogous to QAbstractItemView::moveCursor(), but it does not. In the code below we capture key press and mouse wheel events, which are the only gestures I'm aware of at the moment. If other gestures are also needed, we would need to independently implement each one. Because the Qt architects did not generalize the concepts of "next" and "previous" for these cases the way they did for QAbstractItemView::moveCursor().
The following code defines a replacement class for QComboBox that implements these principles.
from PySide2 import QtCore, QtGui, QtWidgets
from PySide2.QtCore import Qt
# CircularListView allows circular navigation when the ComboBox is expanded to show all items
class CircularListView(QtWidgets.QListView):
"""
CircularListView allows circular navigation.
So moving down from the bottom item selects the top item,
and moving up from the top item selects the bottom item.
"""
def moveCursor(
self,
cursor_action: QtWidgets.QAbstractItemView.CursorAction,
modifiers: Qt.KeyboardModifiers,
) -> QtCore.QModelIndex:
selected = self.selectedIndexes()
if len(selected) != 1:
return super().moveCursor(cursor_action, modifiers)
index: QtCore.QModelIndex = selected[0]
top = 0
bottom = self.model().rowCount() - 1
ca = QtWidgets.QAbstractItemView.CursorAction
# When trying to move up from the top item, wrap to the bottom item
if index.row() == top and cursor_action == ca.MoveUp:
return self.model().index(bottom, index.column(), index.parent())
# When trying to move down from the bottom item, wrap to the top item
elif index.row() == bottom and cursor_action == ca.MoveDown:
return self.model().index(top, index.column(), index.parent())
else:
return super().moveCursor(cursor_action, modifiers)
class CircularCombobox(QtWidgets.QComboBox):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
view = CircularListView(self.view().parent())
self.setView(view)
def _activate_next(self) -> None:
index = (self.currentIndex() + 1) % self.count()
self.setCurrentIndex(index)
def _activate_previous(self):
index = (self.currentIndex() - 1) % self.count()
self.setCurrentIndex(index)
def keyPressEvent(self, event: QtGui.QKeyEvent) -> None:
if event.key() == Qt.Key_Down:
self._activate_next()
elif event.key() == Qt.Key_Up:
self._activate_previous()
else:
super().keyPressEvent(event)
def wheelEvent(self, event: QtGui.QWheelEvent) -> None:
delta = event.angleDelta().y()
if delta < 0:
self._activate_next()
elif delta > 0:
self._activate_previous()
Related
I used a Python3 script under GTK, where I clicked on a link with the left mouse button to open it in the same window and on a middle mouse button to open it in a separate window.
I am now in the process of migrating this script from GTK to Qt6.
The problem is that I cannot intercept the middle mouse button in conjunction with a clicked link:
My browser window is based on QWebEngineView, I can intercept mouse button clicks with an event filter (eventFilter()), and I can intercept clicked links within the acceptNavigationRequest() function of a QWebEnginePage.
The URL of the clicked link is only available in acceptNavigationRequest(), but this function is only called by Qt6 when I use the left mouse button, not, as desired, the middle mouse button (neither does control + left mouse button work).
How can I let a middle mouse button click be recognized in a navigation request?
Debian 11.6 Bullseye, Python 3.9.2, PyQt6-Qt6 6.4.1
With the help of #musicamante (note the comments in the original post), I solved my problem this way:
g_mouse_button = '--'
class MyWebEngineView(QWebEngineView):
def __init__(self):
...
class MyEventFilter(QObject):
def eventFilter(self, obj, event):
global g_mouse_button
...
if event.button() == Qt.MouseButton.MiddleButton:
g_mouse_button = 'middle'
...
...
class MyWebEnginePage(QWebEnginePage):
def acceptNavigationRequest(self, url, ttype, isMainFrame):
global g_mouse_button
if ttype == QWebEnginePage.NavigationType.NavigationTypeLinkClicked and \
g_mouse_button == 'middle':
<open link in new window>
g_mouse_button = '--'
return False # ignore
return True # process
def createWindow(self, window_type):
return self
if __name__ == "__main__":
...
event_filter = MyEventFilter()
g_app.installEventFilter(event_filter)
...
A Qt packing layout, such as QVBoxLayout, can pack widgets inside it, such as buttons. In this case, they will be packed vertically as shown in image below:
When we pack too many widgets inside such a layout, and since scrolling is not added by default, the buttons will eventually get squeezed onto each other up to a point that they will overlap, as shown below:
My questions are:
How to tell Qt to not show/pack widgets beyond the available viewing space in the non-scrolling layout?
How to handle the case when the window is resized? I.e. Qt should add/remove widgets accordingly. E.g. if there is extra space available, then perhaps Qt should add some extra widgets that it couldn't add previously.
To be specific: "too many packed widgets" is when the widgets start invading spaces of other widgets, including their inter-widget spacings or margins.
Appendix
Images above are generated by this code below as run in a tile in i3, which is a modified version of this.
from PyQt5 import QtCore, QtWidgets
app = QtWidgets.QApplication([])
widget = QtWidgets.QWidget()
layout = QtWidgets.QVBoxLayout(widget)
for i in range(40):
layout.addWidget(QtWidgets.QPushButton(str(i + 1)))
widget.show()
app.exec_()
When too many widgets are packed:
If the window is tiled, you see them overcrowded as in in the image.
If the window is floating, the window will keep growing until it is no longer fully visible in the monitor.
None of these outcomes are acceptable in my case. My goal is to have Qt only pack as much as will be visible, and add/remove/hide/show dynamically as the window gets resized.
Try this code. It does not rely on QVBoxLayout but it basically does the same as this layout. It hides the child widgets which are outside of the area. There are no partially visible widgets.
from PyQt5 import QtWidgets
class Container(QtWidgets.QWidget):
_spacing = 5
def __init__(self, parent=None):
super().__init__(parent)
y = self._spacing
for i in range(40):
button = QtWidgets.QPushButton("Button" + str(i + 1), self)
button.move(self._spacing, y)
y += button.sizeHint().height() + self._spacing
def resizeEvent(self, event):
super().resizeEvent(event)
for child in self.children():
if isinstance(child, QtWidgets.QWidget):
child.resize(self.width() - 2 * self._spacing, child.height())
child.setVisible(child.geometry().bottom() < self.height())
app = QtWidgets.QApplication([])
w = Container()
w.resize(500, 500)
w.show()
app.exec_()
Note that is in fact does not add nor remove widgets dynamically, this would be much more code and it would probably be very depending on your specific use case. Moreover it feels as a premature optimization. Unless you really need it, do not do it.
UPDATE:
I experimented with the code above and proposed some improvements. I especially wanted to make it responsive to changes in child widgets. The problem is that if the child widget changes it size, the parent container must be re-layouted. The code above does not react in any way. To make it responsive, we need to react to LayoutRequest event. Note that in the code below, I have created three types of buttons - one add a line to itself, other increases font size, and yet another decreases font size.
from PyQt5 import QtCore, QtWidgets
def changeFontSize(increment):
font = QtWidgets.QApplication.font()
font.setPointSize(font.pointSize() + increment)
QtWidgets.QApplication.setFont(font)
class Container(QtWidgets.QWidget):
_spacing = 5
_children = [] # maintains the order of creation unlike children()
def __init__(self, parent=None):
super().__init__(parent)
for i in range(100):
child = QtWidgets.QPushButton(self)
child.installEventFilter(self)
# these are just to test various changes in child widget itself to force relayout
r = i % 3
if r == 0:
text = "New line"
onClicked = lambda state, w=child: w.setText(w.text() + "\nclicked")
elif r == 1:
text = "Bigger font"
onClicked = lambda: changeFontSize(1)
elif r == 2:
text = "Smaller font"
onClicked = lambda: changeFontSize(-1)
child.setText(text)
child.clicked.connect(onClicked)
self._children.append(child)
def resizeEvent(self, event):
super().resizeEvent(event)
self._relayout()
def event(self, event):
if event.type() == QtCore.QEvent.LayoutRequest:
self._relayout()
return super().event(event)
def _relayout(self):
y = self._spacing
for child in self._children:
h = child.sizeHint().height()
child.move(self._spacing, y)
child.resize(self.width() - 2 * self._spacing, h)
y += h + self._spacing
child.setVisible(y < self.height())
app = QtWidgets.QApplication([])
w = Container()
w.resize(500, 500)
w.show()
app.exec_()
This code is satisfactory, however it is not perfect. I have observed that when the container is being re-layouted and some of the child widgets will change its visibility state, re-layouting is called again. This is not needed but I have not discovered how to prevent it.
Maybe there is some better way...
Requirements:
QScrollArea containing several widgets.
Each widget should be individually resizable by the user (in either horizontal, or vertical, but not both directions).
User resizing of a widget should not change the size of other widgets. It should increase/decrease the area available in the QScrollArea.
Using a QSplitter doesn't help, because the QSplitter remains of fixed width, and resizing any of its splits causes other splits to shrink.
[1] [2] [3]
Surely it can be done by creating a custom widget, adding a visual bar for indicating the draggable area, and listening to a drag event to resize the widget via code. Is there a simpler solution?
I had the same problem. Came up with a nasty hack:
put a QSplitter inside the QScrollArea
store the old sizes of all QSplitter child widgets
when a QSplitterHandle moves (i.e. on SIGNAL splitterMoved() )
Calculate how much the changed child widget has grown/shrunk
Change the min size of the whole QSplitter by that amount
Update my stored size for the changed child widget only
Set the sizes of the QSplitter child widgets to my stored sizes.
It works for me (for now). But it's kludgy, and there are some yucky magic numbers in it to make it work.
So if anyone comes up with a better solution, that would be great!
Anyway - in case anyone finds it useful, Code (in Python3 & PySide2)
import sys
from PySide2.QtCore import Qt
from PySide2.QtWidgets import QWidget, QScrollArea, QSplitter
from PySide2.QtWidgets import QApplication, QMainWindow, QLabel, QFrame
class ScrollSplitter(QScrollArea):
def __init__(self, orientation, parent=None):
super().__init__(parent)
# Orientation = Qt.Horizontal or Qt.Vertical
self.orientation = orientation
# Keep track of all the sizes of all the QSplitter's child widgets BEFORE the latest resizing,
# so that we can reinstate all of them (except the widget that we wanted to resize)
self.old_sizes = []
self._splitter = QSplitter(orientation, self)
# TODO - remove magic number. This is required to avoid zero size on first viewing.
if orientation == Qt.Horizontal :
self._splitter.setMinimumWidth(500)
else :
self._splitter.setMinimumHeight(500)
# In a default QSplitter, the bottom widget doesn't have a drag handle below it.
# So create an empty widget which will always sit at the bottom of the splitter,
# so that all of the user widgets have a handle below them
#
# I tried playing with the max width/height of this bottom widget - but the results were crummy. So gave up.
bottom_widget = QWidget(self)
self._splitter.addWidget(bottom_widget)
# Use the QSplitter.splitterMoved(pos, index) signal, emitted every time the splitter's handle is moved.
# When this signal is emitted, the splitter has already resized all child widgets to keep its total size constant.
self._splitter.splitterMoved.connect(self.resize_splitter)
# Configure the scroll area.
if orientation == Qt.Horizontal :
self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
else :
self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.setWidgetResizable(True)
self.setWidget(self._splitter)
# Called every time a splitter handle is moved
# We basically undo the QSplitter resizing of all the other children,
# and resize the QSplitter (using setMinimumHeight() or setMinimumWidth() ) instead.
def resize_splitter(self, pos, index):
# NOTE: index refs the child widget AFTER the moved splitter handle.
# pos is position relative to the top of the splitter, not top of the widget.
# TODO - find a better way to initialise the old_sizes list.
# Ideally whenever we add/remove a widget.
if not self.old_sizes :
self.old_sizes = self._splitter.sizes()
# The 'index' arg references the QWidget below the moved splitter handle.
# We want to change the QWidget above the moved splitter handle, so...
index_above = index - 1
# Careful with the current sizes - QSplitter has already mucked about with the sizes of all other child widgets
current_sizes = self._splitter.sizes()
# The only change in size we are interested in is the size of the widget above the splitter
size_change = current_sizes[index_above] - self.old_sizes[index_above]
# We want to keep the old sizes of all other widgets, and just resize the QWidget above the splitter.
# Update our old_list to hold the sizes we want for all child widgets
self.old_sizes[index_above] = current_sizes[index_above]
# Increase/decrease the(minimum) size of the QSplitter object to accommodate the total new, desired size of all of its child widgets (without resizing most of them)
if self.orientation == Qt.Horizontal :
self._splitter.setMinimumWidth(max(self._splitter.minimumWidth() + size_change, 0))
else :
self._splitter.setMinimumHeight(max(self._splitter.minimumHeight() + size_change, 0))
# and set the sizes of all the child widgets back to their old sizes, now that the QSplitter has grown/shrunk to accommodate them without resizing them
self._splitter.setSizes(self.old_sizes)
#print(self.old_sizes)
# Add a widget at the bottom of the user widgets
def addWidget(self, widget):
self._splitter.insertWidget(self._splitter.count()-1, widget)
# Insert a widget at 'index' in the splitter.
# If the widget is already in the splitter, it will be moved.
# If the index is invalid, widget will be appended to the bottom of the (user) widgets
def insertWidget(self, index, widget):
if index >= 0 and index < (self._splitter.count() - 1) :
self._splitter.insertWidget(index, widget)
self.addWidget(widget)
# Replace a the user widget at 'index' with this widget. Returns the replaced widget
def replaceWidget(self, index, widget):
if index >= 0 and index < (self._splitter.count() - 1) :
return self._splitter.replaceWidget(index, widget)
# Return the number of (user) widgets
def count(self):
return self._splitter.count() - 1
# Return the index of a user widget, or -1 if not found.
def indexOf(self, widget):
return self._splitter.indexOf(widget)
# Return the (user) widget as a given index, or None if index out of range.
def widget(self, index):
if index >= 0 and index < (self._splitter.count() - 1) :
return self._splitter.widget(index)
return None
# Save the splitter's state into a ByteArray.
def saveState(self):
return self._splitter.saveState()
# Restore the splitter's state from a ByteArray
def restoreState(self, s):
return self._splitter.restoreState(s)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("ScrollSplitter Test")
self.resize(640, 400)
self.splitter = ScrollSplitter(Qt.Vertical, self)
self.setCentralWidget(self.splitter)
for color in ["Widget 0", "Widget 1", "Widget 2", "Some other Widget"]:
widget = QLabel(color)
widget.setFrameStyle(QFrame.Panel | QFrame.Raised)
self.splitter.addWidget(widget)
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()
I'm having a lot of problems getting the details right for my QAbstractScrollArea. This is my current implementation of viewportEvent:
def viewportEvent(self, event):
if event.type() in [QEvent.MouseButtonPress,
QEvent.MouseMove,
QEvent.MouseButtonRelease,
QEvent.ContextMenu,
QEvent.KeyPress,
QEvent.KeyRelease]:
return self.my_viewport.event(event)
if event.type() == QEvent.Resize:
self.my_viewport.resizeEvent(event)
return super().viewportEvent(event)
if event.type() in [QEvent.UpdateLater,
QEvent.UpdateRequest]:
self.my_viewport.event(event)
if event.type() == QEvent.Paint:
self.my_viewport.paintEvent(event)
return super().viewportEvent(event)
The idea is to pass through (to the viewport widget) things like key and mouse presses. Resize events need to be passed through and sent to the abstract-scroll-area itself? What about the size for the scroll bars? Shouldn't the resize event's size be changed. If I don't pass paint events through, the viewport widget doesn't paint.
Minimum working example of broken QOpenGLWidget with QAbstractScrollArea:
import sys
from PyQt5.QtCore import QEvent
from PyQt5.QtWidgets import (QAbstractScrollArea, QApplication, QMainWindow,
QOpenGLWidget)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.scope_view_widget = ScrollingScopeView()
self.setCentralWidget(self.scope_view_widget)
class ScopeView(QOpenGLWidget):
def paintGL(self):
super().paintGL()
print("Painting")
class ScrollingScopeView(QAbstractScrollArea):
def __init__(self):
super().__init__()
self.set_my_viewport(ScopeView())
def set_my_viewport(self, new_viewport):
self.my_viewport = new_viewport
self.setViewport(self.my_viewport)
def viewportEvent(self, event):
# Uncommenting this breaks painting.
if event.type() == QEvent.Paint:
self.my_viewport.paintEvent(event)
return super().viewportEvent(event)
application = QApplication(sys.argv)
main_window = MainWindow()
main_window.show()
sys.exit(application.exec_())
Filed as a Qt bug: https://bugreports.qt.io/browse/QTBUG-53269
My previous answer was absolutely wrong. Kudos to the OP for his investigation.
Per the docs:
When inheriting QAbstractScrollArea, you need to do the following:
Control the scroll bars by setting their range, value, page step, and tracking their movements.
Draw the contents of the area in the viewport according to the values of the scroll bars.
Handle events received by the viewport in viewportEvent() - notably resize events.
Use viewport->update() to update the contents of the viewport instead of update() as all painting operations take place on the viewport.
Unless you need to do other event management, the very short viewportEvent() in your MCVE is correct. Take a look at the code (a better look than I did) and you'll see that most events (including paint events) are not passed to the viewport. Curiously, the code does make an exception to properly resize QOpenGLWidget.
I realize now the logic behind not painting by default is to allow you to update only the region of the viewport currently visible.
In short, the below is fine. I would recommend checking to ensure the paint event only includes the rect currently visible (check the value of rect() in the paint event), otherwise you'll be painting areas not currently visible in your viewport.
def viewportEvent(self, event):
# Uncommenting this breaks painting.
if event.type() == QEvent.Paint:
self.my_viewport.paintEvent(event)
return super().viewportEvent(event)
Apologies for my screwup. I hope this is helpful.
Recently, I want that QListWidgetItem can emit a signal, when the mouse pointer enter. Show a QStackedWidget, when leave, hide the QStackedWidget;
I defined a class My_ListWidget; in the class i override enterEvent and leaveEvent. But this is i hover the QListWidget not the QListWidgetItem, and it always show the first of the QStackedWidget.
override mouseMoveEvent and grab the QListWidgetItem under the cursor with itemAt(event.pos())
edit: instead of overriding mouseEvent you can use the signal entered which will also pass the ModelIndex of the item end then use leaveEvent to clear the stacked widget, you need to activate mouseTracking for this to work
For me, I had some problems with getting the Item via itemAt. When subclassing QListWidget, you can enable mouse tracking with setMouseTracking(True) and use itemEntered and leaveEvent
class My_ListWidgetClass(QListWidget):
def __init__(self):
QListWidget.__init__(self)
self.setMouseTracking(True)
class Main(...):
def __init__(self):
self.centralWidget.connect( self.My_ListWidgetInstance,
SIGNAL('itemEntered(QListWidgetItem *)'),
self.whenItemEntered_doThis)
self.centralWidget.connect( self.My_ListWidgetInstance,
SIGNAL('leaveEvent(QEvent *)'),
self.whenItemLeft_doThis)
def whenItemEntered_doThis(self, QLWItem):
# you can apply behavior here according
# to the QListWidgetItem given as argument
# e. g. get itemtext (itemtext = str(QLWItem.text())
def whenItemLeft_doThis(self, Event):
# executed when an item was left
# unfortunatelly I can't explain, what you
# can do with the event. I didn't need it...