raton
raton

Reputation: 428

pyqt sizehint method is not working without classlevel

if i use QtGui.QWidget in classlevel it gives me the window size by self.sizeHint() method

class MainWin(QtGui.QWidget):
    def __init__(self,parent=None):
        QtGui.QWidget.__init__(self,parent)
        print(self.sizeHint())

but if i use QtGui.QWidget without class just mentioned below.it just printing PyQt4.QtCore.QSize(-1, -1). what is the problem?

app=QtGui.QApplication(sys.argv)
win = QtGui.QWidget()
print(win.sizeHint())
win.setFocusPolicy(QtCore.Qt.StrongFocus)
win.show()


app.exec_()

Upvotes: 0

Views: 1575

Answers (1)

Aleksandar
Aleksandar

Reputation: 3661

The default implementation of sizeHint() returns an invalid size (-1,-1) if there is no layout for widget, and returns the layout's preferred size otherwise. So, you need to set some layout (works for both cases):

from PyQt4 import QtGui, QtCore

class MainWin(QtGui.QWidget):
    def __init__(self,parent=None):
        QtGui.QWidget.__init__(self,parent)
        lay = QtGui.QGridLayout() 
        self.setLayout(lay)
        print "case 1: ", self.sizeHint()

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)

    #case 1   
    win=MainWin()
    win.show()

    #case 2
    win1 = QtGui.QWidget()
    win1.setFocusPolicy(QtCore.Qt.StrongFocus)   
    lay = QtGui.QGridLayout() 
    win1.setLayout(lay)    
    win1.show()
    print "case 2: ", win1.sizeHint()

    sys.exit(app.exec_())

Upvotes: 1

Related Questions