Multi column context menu
-
I would like to have a multi column context menu (or dropdown). I do have 47 items which I am not able to split into multiple sub-menus.
Something like this:
I do have an (ChatGPT; blame on me!) approach using a QContextMenu with a QTableWidget as custom widget. But the size is a problem.
Size of context menu and table widget do not fit. Any ideas about it? This should be a 3 columns and 12 rows context menu.
Code:
from PyQt6.QtWidgets import (QApplication, QMenu, QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget, QWidgetAction) from PyQt6.QtCore import Qt class TwoColumnContextMenu(QWidget): def __init__(self): super().__init__() self.setWindowTitle("Zwei-Spalten-Kontextmenü") self.setGeometry(100, 100, 400, 300) self.init_ui() def init_ui(self): # Einfacher Platzhalter für Rechtsklick self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) self.customContextMenuRequested.connect(self.show_context_menu) def show_context_menu(self, pos): # Benutzerdefiniertes Widget (zwei Spalten) table_widget = QTableWidget(12, 3, self) for col in [0, 1, 2]: for row in range(12): table_widget.setItem(row, col, QTableWidgetItem(f'Option {col}-{row}')) # Spalten- und Zeilenüberschriften ausblenden table_widget.horizontalHeader().setVisible(False) table_widget.verticalHeader().setVisible(False) # Scrollbars entfernen table_widget.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) table_widget.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) # Zellklick-Handler table_widget.cellClicked.connect(self.handle_item_click) # Benutzerdefiniertes Widget in Kontextmenü einfügen action_widget = QWidget() layout = QVBoxLayout(action_widget) layout.addWidget(table_widget) action_widget.setLayout(layout) action = QWidgetAction(self) action.setDefaultWidget(action_widget) # Kontextmenü erstellen menu = QMenu(self) menu.addAction(action) table_widget.adjustSize() menu.setFixedSize(table_widget.size()) # Menü anzeigen menu.exec(self.mapToGlobal(pos)) def handle_item_click(self, row, column): item_text = f"Ausgewählt: {row}, {column}" print(f"Item angeklickt: {item_text}") if __name__ == "__main__": app = QApplication([]) window = TwoColumnContextMenu() window.show() app.exec()
-
-
I tried to make the menu widget the same size as the table widget. But there is no effect.
Without it the menu widget has always the same size, not reacting to its child table widget.
If the table is 3x2 the menu is to big. If the table is 3x12 as in my example the widget is to small. -
@buhtz said in Multi column context menu:
But the elements in the grid need to react as a menu entry
And what is the problem?
The widgets in the grid can do whatever you want.The cells in the table will also not behave like menu entries out of the box.
-
A QTableWidget doesn't seem to be most solution thing for this, you are not presenting data.
A QHboxLayout of QVBoxLayout would be the solution I'd try.