PDA

View Full Version : A question about position of widgets



Tei
1st July 2010, 09:14
Hi all, I am trying to get the position information of widgets, here is my code,

ok = QtGui.QPushButton("OK")
cancel = QtGui.QPushButton("Cancel")

vbox.addWidget(ok)
vbox.addWidget(cancel)
print ok.pos()
print cancel.pos()

which output (0,0) (0,0)
How could I get the actual position of these widgets? Would anyone guide me to make it work? Thanks in advance

high_flyer
1st July 2010, 10:35
Have a look at geometry().

using pos() is correct too, just don't forget that its relative to the parent.
If you want screen position, then have a look at mapToGlobal().

Aster036
1st July 2010, 13:43
Hi,

You can use :

qDebug()<< okbutton->x() << okbutton->y();
qDebug()<< cancelButton->x() << cancelButton->y();

Again as said x() holds the x coordinate of the widget relative to its parent including any window frame.By default, this property has a value of 0.

Tei
1st July 2010, 15:52
I still can't get this work. here is my code, I don't know what's wrong here.

import sys
from PyQt4 import QtGui


class BoxLayout(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)

self.setWindowTitle('box layout')

self.ok = QtGui.QPushButton("OK", self)
self.cancel = QtGui.QPushButton("Cancel", self)

vbox = QtGui.QVBoxLayout()
vbox.addStretch(1)
vbox.addWidget(self.ok)
vbox.addWidget(self.cancel)

print self.ok.geometry()
print self.ok.parent()
print self.cancel.geometry()
print self.cancel.parent()
print self.ok.mapToParent(self.ok.pos())
print self.mapToParent(self.ok.pos())
print self.mapToGlobal(self.ok.pos())


self.setLayout(vbox)

self.resize(300, 150)

app = QtGui.QApplication(sys.argv)
qb = BoxLayout()
qb.show()
sys.exit(app.exec_())

aamer4yu
1st July 2010, 16:24
The positions are not properly calculated unless the widget is shown. So I doubt you getting proper values :rolleyes:

Tei
1st July 2010, 16:35
oh yes, I got it. The 'print' should be put after 'show', thank you guys a lot.