I have a GUI where a QListWidget is the central widget. The QListWidgetItems are composed of a custom widget that include a Graphics area and a QTable.
When I click on the graphics area, or on the table, the parent QListWidgetItem is not selected
See Picture of the GUI I'm working on
The red border around the top QListWidgetItem indicates that is the one that is currently selected.
From the Input on the table in the second QListWidgetItem, you can see I'm inputting text into the table widget there.
How can I make it so that if I click anywhere on that QListWidgetItem, including its child widgets, that the corresponding item is selected?
For reference, here is some of the relevant code:
class MainWindow(QMainWindow):
move_splitter = Signal(int, int)
def __init__(self):
super().__init__()
# stuff
self.panels = QListWidget()
self.panels.setAcceptDrops(True)
self.panels.setDragEnabled(True)
self.panels.setDragDropMode(QAbstractItemView.InternalMove)
self.panels.setStyleSheet("QListWidget::item:selected \
{ border: 1px solid red }")
self.panels.setSelectionMode(QAbstractItemView.SingleSelection)
self.setCentralWidget(self.panels)
# more stuff
def add_panel(self):
insert_item = QListWidgetItem()
# Panel inherits from QWidget
new_panel = Panel(parent=insert_item,
splitter_pos=self.initialSplitterPosition)
self.move_splitter.connect(new_panel.setSplitterPosition)
new_panel.slider_position.connect(self.slotSplitterPosition)
insert_item.setSizeHint(new_panel.sizeHint())
insert_item.setFlags(insert_item.flags() | Qt.ItemIsAutoTristate)
insert_item.setCheckState(Qt.PartiallyChecked)
self.panels.insertItem(self.panels.currentRow() + 1, insert_item)
self.panels.setItemWidget(insert_item, new_panel)
EDIT:
With the suggestion of implementing an event filter, I created the following subclass of my table
class ControlTable(QTableWidget):
focusReceived = Signal()
def __init__(self, parent=None):
super().__init__()
def focusInEvent(self, event):
if event.type() == QFocusEvent.gotFocus:
self.focusReceived.emit()
QTableWidget.focusInEvent(self, event)
In my panel function, I created a signal and a slot to capture that signal and emit a signal to the MainWindow with which QListWidgetItem should be selected
class Panel(QWidget):
slider_position = Signal(int, int)
select_me = Signal(QObject)
def __init__(self, parent=None, splitter_pos=[]):
# stuff
self.table = ControlTable()
self.table.focusReceived.connect(self.childWidgetFocus)
# more stuff
#Slot()
def childWidgetFocus(self):
parent = self.parent_item
self.select_me.emit(parent)
In my mainwindow class I also added
def add_panel(self):
insert_item = QListWidgetItem()
new_panel = Panel(parent=insert_item,
splitter_pos=self.initialSplitterPosition)
new_panel.parent_item = insert_item
new_panel.select_me.connect(self.changeSelection)
# more stuff
#Slot(QObject)
def changeSelection(self, item):
item.setSelected(True)
While the code runs, the change of selection is not happening, am I implementing the wrong event filter?
EDIT2:
Got it working, was using the wrong event filter type, I needed to use QEvent.FocusIn, but now that I look at my code, and looking at the function I'm overwriting, that if statement is unnecessary it would seem.
I also had to change the signal pass type from QObject to QListWidgetItem.
One possible but long way could be to set an event filter on each child of the item's widget (in your case its Panel) and select the the QListWidgetItem bound to the parent (Panel) from that event filter when focus is on the child element.
You can store the item reference in item attribute of Panel widget (you should create it) to make the item selection easier. So add before setItemWidget
new_panel.item = insert_item
In your event filter you can emit pyqtSignal passing self.parent().item as a parameter and further process it to select the corresponding item
some references which should help you to start:
How to change a parent widget's background when a child widget has focus?
Related
Using Qt5 I am trying to make a widget work using absolute positioning. The code below is a minimum working example of something I am trying to do. A quick walk through of the code:
CentralWidget is the central widget of the main window and holds MyWidget using absolute positioning, e.g. without using any layouts.
MyWidget does not set its child widgets immediately but provides a SetData method which first removes all current child widgets and then adds the new child widgets to its layout.
SetData is triggered using a timer in the main window.
I commented out two lines of code. The first "enables" relative positioning using layouts by adding a layout to CentralWidget. This line shows what I am trying to achieve but with absolute positioning. The second comment enables some debug information:
MyWidget
layout.count: 3
size: PyQt5.QtCore.QSize(-1, -1)
sizeHint: PyQt5.QtCore.QSize(200, 100)
CentralWidget
size: PyQt5.QtCore.QSize(18, 18)
sizeHint: PyQt5.QtCore.QSize(18, 18)
What I am doing wrong in order for MyWidget to be visible using absolute positioning?
Code:
from PyQt5 import QtCore, QtWidgets
import sys
class MyWidget(QtWidgets.QWidget):
z = 0
def __init__(self, parent):
super().__init__(parent)
self._layout = QtWidgets.QVBoxLayout(self)
def SetData(self):
while self._layout.count() > 0:
widget = self._layout.takeAt(0).widget()
widget.hide()
widget.deleteLater()
for i in range(3):
self._layout.addWidget(QtWidgets.QLabel(str(MyWidget.z * 10 + i)))
MyWidget.z += 1
class CentralWidget(QtWidgets.QWidget):
def __init__(self, parent):
super().__init__(parent)
self._myWidget = MyWidget(self)
# QtWidgets.QHBoxLayout(self).addWidget(self._myWidget)
def SetData(self):
self._myWidget.SetData()
# print("MyWidget\n layout.count: {}\n size: {}\n sizeHint: {}\n\nCentralWidget\n size: {}\n sizeHint: {}\n\n".format(self._myWidget.layout().count(), self.sizeHint(), self.size(), self._myWidget.sizeHint(), self._myWidget.size()))
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
centralWidget = CentralWidget(self)
self.setCentralWidget(centralWidget)
self._timer = QtCore.QTimer(self)
self._timer.timeout.connect(centralWidget.SetData)
self._timer.start(500)
def main():
app = QtWidgets.QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
app.exec_()
if __name__ == "__main__":
main()
The reason for this behavior is directly related to the fact that the widget is not added to a layout and its contents are added after being shown.
In fact, if you call centralWidget.SetData() upon initialization and before mainWindow.show(), it will work as expected.
A lot of things happen when you add a child widget to a layout, and this usually involves multiple calls to the children size hints, allowing the parent to adapt its own size hint, and, after that, adapt its size and that of its children.
If that "container widget" is itself contained in another layout, that widget will be automatically resized (based on its hint) in the next cycle of events, but this doesn't happen in your case, since yours is a "free" widget.
The function you are looking for is QWidget.adjustSize(), but, for the aforementioned reasons, you cannot call it immediately after adding the children widgets.
To overcome your issue, you can call QApplication.processEvents() before adjustSize(), or, eventually, use a 0-based single shot QTimer:
def SetData(self):
while self._layout.count() > 0:
widget = self._layout.takeAt(0).widget()
widget.hide()
widget.deleteLater()
for i in range(3):
self._layout.addWidget(QtWidgets.QLabel(str(MyWidget.z * 10 + i)))
MyWidget.z += 1
QtCore.QTimer.singleShot(0, self.adjustSize)
I want to create a menu with a checkable list. To prevent the menu from closing when the action is clicked, I'm setting the DefaultWidget to be a QCheckBox. The problem is when I'm trying to get isClicked from the action - it doesn't seem to be synced to the checkbox. How do I get the value of the action to change when the checkbox is clicked?
tool_button = QtWidgets.QToolButton()
menu = QtWidgets.QMenu()
check_box = QtWidgets.QCheckBox(menu)
check_box.setText("abc")
check_box.setChecked(True)
action_button = QtWidgets.QWidgetAction(menu)
action_button.setDefaultWidget(check_box)
menu.addAction(action_button)
tool_button.setMenu(menu)
print(check_box.text()) # returns abc
print(check_box.isChecked()) # returns True
print(action_button.isChecked()) # returns False - it's not picking up the values from check_box
Since QWidgetAction acts as some sort of container for any kind of widget, it has no way to know if its defaultWidget could even have any support for a bool state like "isChecked", so you have to provide it.
The simplest way is to subclass a specific QWidgetAction class for that action, and override its isChecked() method so that it returns the checked value based on its default widget.
from PyQt5 import QtWidgets
class CheckableWidgetAction(QtWidgets.QWidgetAction):
def setDefaultWidget(self, widget):
super().setDefaultWidget(widget)
try:
# if the widget has the toggled signal, connect that signal to the
# triggered signal
widget.toggled.connect(self.triggered)
except:
pass
def isChecked(self):
try:
return self.defaultWidget().isChecked()
except:
# failsafe, in case no default widget has been set or the provided
# widget doesn't have a "checked" property
return super().isChecked()
class Test(QtWidgets.QWidget):
def __init__(self):
super().__init__()
layout = QtWidgets.QVBoxLayout(self)
tool_button = QtWidgets.QToolButton()
layout.addWidget(tool_button)
menu = QtWidgets.QMenu()
check_box = QtWidgets.QCheckBox(menu)
check_box.setText("abc")
check_box.setChecked(True)
self.action_button = CheckableWidgetAction(menu)
self.action_button.setDefaultWidget(check_box)
self.action_button.triggered.connect(self.action_triggered)
menu.addAction(self.action_button)
tool_button.setMenu(menu)
controlButton = QtWidgets.QPushButton('is checked?')
layout.addWidget(controlButton)
controlButton.clicked.connect(self.is_checked)
def is_checked(self):
print('checked is {}'.format(self.action_button.isChecked()))
def action_triggered(self, state):
print('triggered {}'.format(state))
if __name__ == '__main__':
import sys
a = QtWidgets.QApplication(sys.argv)
test = Test()
test.show()
sys.exit(a.exec_())
I'm trying to change the cursor shape on key event:
When i press 'C', i want to display a LineCursor,
when i press 'S', i want to display a CrossCursor, and
when i press 'N', i want to display the standard ArrowCursor.
The cursor change only if it leave the canvas and return to it,
but not if the cursor stay in the canvas.
self.update() on the canvas don't work
Here the code to reproduce the problem :
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setObjectName("MainWindow")
self.resize(942, 935)
self.centralwidget = QWidget(self)
self.centralwidget.setObjectName("centralwidget")
self.horizontalLayout = QHBoxLayout(self.centralwidget)
self.horizontalLayout.setObjectName("horizontalLayout")
self.MainView = QGraphicsView(self.centralwidget)
self.MainView.setObjectName("MainView")
self.horizontalLayout.addWidget(self.MainView)
self.setCentralWidget(self.centralwidget)
self.setWindowTitle("MainWindow")
self.scene = QGraphicsScene( 0.,0., 1240., 1780. )
self.canvas = Canvas()
self.widget = QWidget()
box_layout = QVBoxLayout()
self.widget.setLayout(box_layout)
box_layout.addWidget(self.canvas)
self.scene.addWidget(self.widget)
self.MainView.setScene(self.scene)
self.MainView.setRenderHints(QPainter.Antialiasing)
self.MainView.fitInView(0, 0, 45, 55, Qt.KeepAspectRatio)
self.show()
empty = QPixmap(1240, 1748)
empty.fill(QColor(Qt.white))
self.canvas.newPixmap(empty)
def keyPressEvent(self, e):
key = e.key()
if key == Qt.Key_C:
self.canvas.setCutCursor()
elif key == Qt.Key_N:
self.canvas.setNormalCursor()
elif key == Qt.Key_S:
self.canvas.setSelectionCursor()
class Canvas(QLabel):
def __init__(self):
super().__init__()
sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
self.setSizePolicy(sizePolicy)
self.setAlignment(Qt.AlignLeft)
self.setAlignment(Qt.AlignTop)
def newPixmap(self, pixmap):
self.setPixmap(pixmap)
def setCutCursor(self):
newCursor = QPixmap(500,3)
newCursor.fill(QColor("#000000"))
self.setCursor(QCursor(newCursor))
def setSelectionCursor(self):
self.setCursor(Qt.CrossCursor)
def setNormalCursor(self):
self.setCursor(QCursor(Qt.ArrowCursor))
if __name__ == '__main__':
app = QApplication(sys.argv)
mainWindow = MainWindow()
sys.exit(app.exec_())
It seems to be an old bug that was never resolved: setCursor on QGraphicsView don't work when add QWidget on the QGraphicsScene
There is a possible workaround, but it's far from perfect.
First of all, you have to consider that while dealing with a QGraphicsScene and its view[s] is not easy when dealing with mouse events and widget proxies, mostly because of the multiple nested levels of events and interaction between the actual view (and its parent, up to the top level window) and the proxy itself, which is an abstraction of the widget you added to the scene. While Qt devs did a huge amount of work to make it as transparent as possible, at some point you will probably face some unexpected or undesired behavior that is usually hard to fix or work around, and that's also because a graphics scene might be visualized in more than a single view.
Besides the aforementioned bug, you have to consider that a graphics view uses QWidget.setCursor internally whenever any of its items call setCursor on themselves, and since the view is a very complex widget, at some point it might even try to "restore" the cursor if it thinks it should (even if it shouldn't).
Finally, some events which also have something to do with focus might become in the way of all that.
The first workaround is to set the cursor to the view itself (or, better, the view's viewport, which is the actual widget that shows the scene contents). To ensure that, we obviously need to check if the cursor is inside the canvas.
Unfortunately, because of the event handling written above, this could become a bit messy, as some events are even delayed by at least a cycle within the main Qt event loop; the result is that while setting a cursor the first time might work, setting it again might not, and even if it would, it's possible that the cursor will not be applied until the mouse is moved at least by one pixel.
As a second workaround, we need an event filter to bypass all that and check the cursor whenever the mouse is moved within the viewport margins.
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
# ...
self.show()
empty = QPixmap(1240, 1748)
empty.fill(QColor(Qt.darkGray))
self.canvas.newPixmap(empty)
# install an event filter on the view's viewport;
# this is very, *VERY* important: on the *VIEWPORT*!
# if you install it on the view, it will *not* work
self.MainView.viewport().installEventFilter(self)
def insideCanvasRect(self, pos):
canvasRect = self.canvas.rect()
# translate the canvas rect to its top level window to get the actual
# geometry according to the scene; we can't use canvas.geometry(), as
# geometry() is based on the widget's parent coordinates, and that
# parent could also have any number of parents in turn;
canvasRect.translate(self.canvas.mapTo(self.canvas.window(), QPoint(0, 0)))
# map the geometry to the view's transformation, which probably uses
# some scaling, but also translation *and* shearing; the result is a
# polygon, as with shearing you could transform a rectangle to an
# irregular quadrilateral
polygon = self.MainView.mapFromScene(QRectF(canvasRect))
# tell if the point is within the resulting polygon
return polygon.containsPoint(pos, Qt.WindingFill)
def eventFilter(self, source, event):
if source == self.MainView.viewport() and (
(event.type() == QEvent.MouseMove and not event.buttons()) or
(event.type() == QEvent.MouseButtonRelease)
):
# process the event
super(MainWindow, self).eventFilter(source, event)
if self.insideCanvasRect(event.pos()):
source.setCursor(self.canvas.cursor())
else:
source.unsetCursor()
# usually a mouse move event within the view's viewport returns False,
# but in that case the event would be propagated to the parents, up
# to the top level window, which might reset the *previous* cursor
# at some point, no matter if we try to avoid that; to prevent that
# we return True to avoid propagation.
# Note that this will prevent any upper-level filtering and *could*
# also create some issues for the drag and drop framework
if event.type() == QEvent.MouseMove:
return True
return super(MainWindow, self).eventFilter(source, event)
def keyPressEvent(self, e):
# send the canvas a fake leave event
QApplication.sendEvent(self.canvas, QEvent(QEvent.Leave))
key = e.key()
if key == Qt.Key_C:
self.canvas.setCutCursor()
elif key == Qt.Key_N:
self.canvas.setNormalCursor()
elif key == Qt.Key_S:
self.canvas.setSelectionCursor()
pos = self.canvas.rect().center()
event = QEnterEvent(pos, self.canvas.mapTo(self.canvas.window(), pos), self.canvas.mapToGlobal(pos))
# send a fake enter event (mapped to the center of the widget, just to be sure)
QApplication.sendEvent(self.canvas, event)
# if we're inside the widget, set the view's cursor, otherwise it will not
# be set until the mouse is moved
if self.insideCanvasRect(self.MainView.viewport().mapFromGlobal(QCursor.pos())):
self.MainView.viewport().setCursor(self.canvas.cursor())
This question is similar to the one in this this topic Preserve QStandardItem subclasses in drag and drop but with issue that I cant find a good solution for. That topic partially helps but fail on more complex task.
When I create an item in QTreeView I put that item in my array but when I use drag&Drop the item gets deleted and I no longer have access to it. I know that its because drag and drop copies the item and not moves it so I should use setData. I cant setData to be an object because even then the object gets copied and I lose reference to it.
Here is an example
itemsArray = self.addNewRow
def addNewRow(self)
'''some code with more items'''
itemHolder = QStandardItem("ProgressBarItem")
widget = QProgressBar()
itemHolder.setData(widget)
inx = self.model.rowCount()
self.model.setItem(inx, 0, itemIcon)
self.model.setItem(inx, 1, itemName)
self.model.setItem(inx, 2, itemHolder)
ix = self.model.index(inx,2,QModelIndex())
self.treeView.setIndexWidget(ix, widget)
return [itemHolder, itemA, itemB, itemC]
#Simplified functionality
data = [xxx,xxx,xxx]
for items in itemsArray:
items[0].data().setPercentage(data[0])
items[1].data().setText(data[1])
items[2].data().setChecked(data[2])
The code above works if I won't move the widget. The second I drag/drop I lose reference I lose updates on all my items and I get crash.
RuntimeError: wrapped C/C++ object of type QProgressBar has been deleted
The way I can think of of fixing this problem is to loop over entire treeview recursively over each row/child and on name match update item.... Problem is that I will be refreshing treeview every 0.5 second and have 500+ rows with 5-15 items each. Meaning... I don't think that will be very fast/efficient... if I want to loop over 5 000 items every 0.5 second...
Can some one suggest how I could solve this problem? Perhaps I can edit dropEvent so it does not copy/paste item but rather move item.... This way I would not lose my object in array
Qt can only serialize objects that can be stored in a QVariant, so it's no surprise that this won't work with a QWidget. But even if it could serialize widgets, I still don't think it would work, because index-widgets belong to the view, not the model.
Anyway, I think you will have to keep references to the widgets separately, and only store a simple key in the model items. Then once the items are dropped, you can retrieve the widgets and reset them in the view.
Here's a working demo script:
from PyQt4 import QtCore, QtGui
class TreeView(QtGui.QTreeView):
def __init__(self, *args, **kwargs):
super(TreeView, self).__init__(*args, **kwargs)
self.setDragDropMode(QtGui.QAbstractItemView.InternalMove)
self.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
self.setAllColumnsShowFocus(True)
self.setModel(QtGui.QStandardItemModel(self))
self._widgets = {}
self._dropping = False
self._droprange = range(0)
def dropEvent(self, event):
self._dropping = True
super(TreeView, self).dropEvent(event)
for row in self._droprange:
item = self.model().item(row, 2)
self.setIndexWidget(item.index(), self._widgets[item.data()])
self._droprange = range(0)
self._dropping = False
def rowsInserted(self, parent, start, end):
super(TreeView, self).rowsInserted(parent, start, end)
if self._dropping:
self._droprange = range(start, end + 1)
def addNewRow(self, name):
model = self.model()
itemIcon = QtGui.QStandardItem()
pixmap = QtGui.QPixmap(16, 16)
pixmap.fill(QtGui.QColor(name))
itemIcon.setIcon(QtGui.QIcon(pixmap))
itemName = QtGui.QStandardItem(name.title())
itemHolder = QtGui.QStandardItem('ProgressBarItem')
widget = QtGui.QProgressBar()
widget.setValue(5 * (model.rowCount() + 1))
key = id(widget)
self._widgets[key] = widget
itemHolder.setData(key)
model.appendRow([itemIcon, itemName, itemHolder])
self.setIndexWidget(model.indexFromItem(itemHolder), widget)
class Window(QtGui.QWidget):
def __init__(self):
super(Window, self).__init__()
self.treeView = TreeView()
for name in 'red yellow green purple blue orange'.split():
self.treeView.addNewRow(name)
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.treeView)
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window()
window.setGeometry(500, 150, 600, 400)
window.show()
sys.exit(app.exec_())
I have a code which consists of 3 classes. The classes widget1 and widget2 inherit from QFrame class and consists of several lineedit and combobox for the user to enter information.
So, what I want is: when the program is launched, it will firstly bring up the QMainWindow class with widget1 set as the central widget.
The widget1 has a Check function which is connected to a button on it. The check button will check whether a condition is true based on the data entered by the user on the page.
If the condition is true. I want the widget2 to set it as central wiget of MainWindow to replace existing central widget, the widget1.
My question is, how do I set the widget2 as the central widget of existing MainWidnow class instance?
This is the format of my code:
class widget1(QtGui.QFrame):
def __init__(self,parent = None):
......
......
def Check(self):
if (condition):
#set widget2 as central widget on MainWindow
class widget2(QtGui.QFrame):
def __int__(self,parent = None):
.....
.....
class MainWindow(QtGui.QMainWindow):
def __init__(self,parent = None):
QtGui.QMainWindow.__init__(self,parent)
....
mywidgetone = widget1()
self.setCentralWidget(mywidgetone)
if __name__ == '__main__':
app = QtGui.QApplicaiton(sys.argv)
main = MainWindow()
main.show()
app.exec_()
I'd do the following for MainWindow:
class MainWindow(QtGui.QMainWindow):
def __init__(self,parent = None):
QtGui.QMainWindow.__init__(self,parent)
....
self.setMyCentral(widget1)
def setMyCentral(self, widgetClass):
mywidget = widgetClass(self)
self.setCentralWidget(mywidget)
and then, in widget1:
def Check(self):
if (condition):
self.parent().setMyCentral(widget2)
Now, please, follow the conventions: classes start in capital letters (Widget1, Widget2) and methods don't (check instead of Check)
Another option is a panel creates all 3 widgets but set widget2 and 3 visible = false. Then when time to change, set widget1 visible=false, and widget2 visible. Etc. You set the panel as central widget, this never changes. Just the panel decides which one of its three children to show.