How to move a child window relative to a parent window in PyQt5?

1k Views Asked by At

I have the following code, but I want the new window to not set exactly in the center of the main window. I would prefer to move it to the left a little (for example 20 px left, and 20 px up), I have tried moveTo() and moveLeft(), but could not really figure it out. I could manage with the topLeft(), but then it is not relative to the main window. The code is below for centering. The question is how to alter my code to get the mentioned result above?

class Form(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.ui = Ui_suffix_editor_panel()
        self.ui.setupUi(self)

        self.suffix_list = Suffix_window(parent=self)
        
        self.ui.show.clicked.connect(self.show_all_suffix_list)
        
        self.show()


    def show_all_suffix_list(self):
        
        self.suffix_list.ui.all_suffix_list.clear()
        open_known_list = open("known.txt", "r")
        for known in open_known_list.read().split('\n'):
            self.suffix_list.ui.all_suffix_list.insertItem(0, known)
            self.suffix_list.show()



class Suffix_window(QWidget):
    def __init__(self, parent=None):
        self.parent = parent
        QWidget.__init__(self)
        self.ui = Ui_suffix_widget()
        self.ui.setupUi(self)


        self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
        self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
        self.ui.exit_list_view.clicked.connect(lambda: self.close())

    def showEvent(self, event):
        if not event.spontaneous():
            geo = self.geometry()
            geo.moveLeft(self.parent.geometry().left())
            QtCore.QTimer.singleShot(0, lambda: self.setGeometry(geo))

It is looks like this: enter image description here

Desired result: enter image description here

1

There are 1 best solutions below

1
On BEST ANSWER

One way to solve this is to first centre the child rect relative the parent rect, and then translate the result by a relative offset:

class Form(QMainWindow):
    ...    

    def show_all_suffix_list(self):            
        self.suffix_list.ui.all_suffix_list.clear()
        open_known_list = open("known.txt", "r")
        for known in open_known_list.read().split('\n'):
            self.suffix_list.ui.all_suffix_list.insertItem(0, known)

        # set initial size
        rect = QtCore.QRect(0, 0, 300, 300)
        # centre on parent
        rect.moveCenter(self.geometry().center())
        # adjust by relative offset (negative values go left/up)
        rect.translate(QtCore.QPoint(-50, 0))

        self.suffix_list.setGeometry(rect)
        self.suffix_list.show()