Spencer
Spencer

Reputation: 2110

get QRect of menus in QMenuBar

I am re-implementing the mouseMoveEvent in a QMenuBar to allow me to click-drag a frameless application around (basically just making my own frame around my app). However I am trying to disable this behavior whenever the mouse is over a QMenu item, which gives strange behavior (the windows starts following your mouse when you click on a menu!).

I thought this would be as simple as calling the QMenuBar's self.childrenRect().contains(event.pos()) however this does not work. From what I can tell self.childrenRect() does not actually return the rect of the QMenu items. So what is the "correct" way to do this?

Here's my subclassed QMenuBar for reference:

class MoveMenu(QtGui.QMenuBar):
    def __init__(self):
        super(MoveMenu, self).__init__()
        self.mouseStartLoc = QtCore.QPoint(0,0)
        self.set_move = False

    def mousePressEvent(self, event):
        super(MoveMenu, self).mousePressEvent(event)
        self.mouseStartLoc = event.pos()

        # this is always testing False
        if not self.childrenRect().contains(event.pos()):
            self.set_move = True

    def mouseMoveEvent(self, event):
        super(MoveMenu, self).mouseMoveEvent(event)
        if self.set_move:
            globalPos = event.globalPos()
            self.parent().move(globalPos - self.mouseStartLoc)

    def mouseReleaseEvent(self, event):
        super(MoveMenu, self).mouseReleaseEvent(event)
        self.set_move = False

Upvotes: 0

Views: 59

Answers (1)

Spencer
Spencer

Reputation: 2110

With help from eyllanesc, here's the working code. self.childrenRect() doesn't work (bug?) but looping manually through the children does.

class MoveMenu(QtGui.QMenuBar):
    def __init__(self):
        super(MoveMenu, self).__init__()
        self.mouseStartLoc = QtCore.QPoint(0,0)
        self.set_move = False

    def mousePressEvent(self, event):
        super(MoveMenu, self).mousePressEvent(event)
        self.mouseStartLoc = event.pos()

        if not any(child.rect().contains(event.pos()) for child in self.children():
            self.set_move = True

    def mouseMoveEvent(self, event):
        super(MoveMenu, self).mouseMoveEvent(event)
        if self.set_move:
            globalPos = event.globalPos()
            self.parent().move(globalPos - self.mouseStartLoc)

    def mouseReleaseEvent(self, event):
        super(MoveMenu, self).mouseReleaseEvent(event)
        self.set_move = False

Upvotes: 0

Related Questions