1

I've created window with button named "First", the window shows me next button named "Second" after clicking on the button "First", but button "Second" isn't moved by:

self.b2.move(50,50)

Whats the problem?

import sys
from PyQt5 import QtWidgets

class Window(QtWidgets.QMainWindow):

   def __init__(self):

       super().__init__()
       self.init_UI()

   def init_UI(self):

       self.Centr= QtWidgets.QWidget()
       self.setCentralWidget(self.Centr)

       self.window = QtWidgets.QStackedWidget(self.Centr)
       self.b1 = self.addButton()
       self.window.addWidget(self.b1)
       self.b2 = self.addButton_2()
       self.b2.move(50,50)
       self.window.addWidget(self.b2)

       self.b1.clicked.connect(self.b1_clk)

       self.currentStack(0)

       self.show()

   def addButton(self): 
       b1 = QtWidgets.QPushButton("First")
       return b1

   def addButton_2(self):  
       b2 = QtWidgets.QPushButton("Second")
       return b2

   def b1_clk(self):
       self.currentStack(1)

   def currentStack(self, index):
      self.window.setCurrentIndex(index)

app = QtWidgets.QApplication(sys.argv)
w = Window()
sys.exit(app.exec_())

Sorry for my English. And thank you for your attention!

Artem Getmanskiy
  • 193
  • 2
  • 16

1 Answers1

1

The button is moved, but then it's immediately added to the QStackedWidget, which will change the parenting and undo the move. Plus, with a QStackedWidget, the child widgets size and position are controlled by the size and position of the QStackedWidget

Brendan Abel
  • 35,343
  • 14
  • 88
  • 118
  • Thank you! But how can I move button in window? I'm trying by `self.window.b2.move(50,50)` after adding button into window widget and catch: _'QStackedWidget' object has no attribute 'b2'_ – Artem Getmanskiy Apr 05 '18 at 08:28
  • Will it better tactic to add all buttons in different _CentralWidget_, then add all _CentralWidget_ in _QStackedWidget_ and managing its by _QStackedWidget_ methods? – Artem Getmanskiy Apr 05 '18 at 08:37
  • @ArtemGetmanskiy You generally shouldn't be using the move command. Very few widgets are hard positioned. People generally use `QLayouts` and spacers to position their widgets. You should probably add a `QWidget` to the stacked widget and position the button inside that with a layout and some spacer items. – Brendan Abel Apr 05 '18 at 17:08
  • Also, if you find the answer helpful, you should generally upvote. – Brendan Abel Apr 05 '18 at 17:08