Issue
Let's say I have a GUI:
When I click the left
button, I expect the object
would locate at left just like:
layout.addWidget(object)
layout.addStretch()
How can I dynamically change the position?
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys
class Widget(QWidget):
def __init__(self):
super().__init__()
layout = QVBoxLayout()
self.setLayout(layout)
self.btnPos = QPushButton('left')
self.btnPos.clicked.connect(self.btnClick)
self.btnLayout = QHBoxLayout()
self.btn = QPushButton('object')
self.btnLayout.addStretch()
self.btnLayout.addWidget(self.btn)
self.btnLayout.addStretch()
layout.addWidget(self.btnPos)
layout.addLayout(self.btnLayout)
def btnClick(self, check=False):
print('click')
pass
if __name__ == '__main__':
app = QApplication(sys.argv)
win = Widget()
win.show()
app.exec_()
Solution
In your btnClick function, you can set the Stretch parameter for each item in self.btnLayout
. In this case you want to set the Stretch for the spacer on the left to 0 and the right spacer to 1:
def btnClick(self, check=False):
print('click')
# align button left
self.btnLayout.setStretch(0,0)
self.btnLayout.setStretch(1,1)
self.btnLayout.setStretch(2,1)
pass
For centering the button, set left and right spacers stretch to 1:
# button is centered
self.btnLayout.setStretch(0,1)
self.btnLayout.setStretch(1,1)
self.btnLayout.setStretch(2,1)
And to align button on right, set left spacer to 1, right spacer to zero:
# align button right
self.btnLayout.setStretch(0,1)
self.btnLayout.setStretch(1,1)
self.btnLayout.setStretch(2,0)
Answered By - bfris
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.