Reputation: 1673
I'm having troubles setting dimensions of a child-QWidget right after it is added to a parent-QWidget. The issue is that it simply doesn't set the geometry:
from PyQt4 import QtCore, QtGui
class MyWidget(QtGui.QWidget):
def __init__(self):
super(MyWidget, self).__init__()
self.initUI()
def initUI(self):
# setting up parent QWidget
self.setMinimumSize(256, 256)
self.setMaximumSize(256, 256)
self.GL = QtGui.QGridLayout(self)
self.GL.setMargin(0)
# setting up child QWidget
self.GL.myWidget2 = QtGui.QFrame()
self.GL.myWidget2.setMinimumSize(128, 128)
self.GL.myWidget2.setMaximumSize(128, 128)
self.GL.myWidget2.setStyleSheet("background: orange")
# attaching child to parent
self.GL.addWidget(self.GL.myWidget2)
# trying to reposition child in parent's local space
self.GL.myWidget2.setGeometry(QtCore.QRect(0, 128, self.width(), self.height()))
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
widget = MyWidget()
widget.show()
app.exec_()
Adding a timer that sets the geometry after a short delay does work though... (replacing self.GL.myWidget2.setGeometry([...])
with):
timer = QtCore.QTimer()
timer.singleShot(10, self.updatePosition)
def updatePosition(self):
self.GL.myWidget2.setGeometry(QtCore.QRect(0, 128, self.width(), self.height()))
...so I suspect the addWidget(...) method to be doing a callback e.g. that redraws the widget in its default position while the main thread has already passed the self.GL.myWidget2.setGeometry([...])
line.
This is purely speculative though, any inside into how addWidget()
affects following coder or execution timing would be much appreciated!
Upvotes: 2
Views: 5041
Reputation:
If you want to position your widget manually, there is no need for a layout:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class orange(QWidget):
def __init__(self, parent=None):
super(orange, self).__init__(parent)
self.setMinimumSize(256, 256)
self.setMaximumSize(256, 256)
self.frame = QFrame(self)
self.frame.setMinimumSize(128, 128)
self.frame.setMaximumSize(128, 128)
self.frame.setGeometry(QRect(0, 128, self.width(), self.height()))
self.frame.setStyleSheet("background: orange")
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
main = orange()
main.show()
sys.exit(app.exec_())
Upvotes: 3