Derrick Zhang
Derrick Zhang

Reputation: 21501

How to make QDIalog auto-resize to the size of its content?

I'm using PyQt4.

I want to show a QTableWidget in a QDialog, and here's the code I use:

    w = QDialog()
    layout = QGridLayout()
    tw = QTableWidget(w)

    ... code to setup tw ...

    layout.addWidget(tw, 0, 0)
    w.setLayout(layout)
    w.exec_():

The resulting QDialog works fine except that it only shows a part of the QTableWidget however many columns are in the table. So I have to drag the border to resize it.

Is there a way to make the QDialog automatically resize to the right size at first ?

I tried to use adjustSize() and setSizePolicy(QSizePolicy(QSizePolicy.Expanding)) but neither of them worked.

Thanks.

Upvotes: 6

Views: 7211

Answers (2)

raton
raton

Reputation: 428

you can try

       w.resize(tw.width(),tw.height())

Upvotes: 1

Aleksandar
Aleksandar

Reputation: 3661

set your table like this:

tw.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
tw.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
tw.horizontalHeader().hide()          
tw.verticalHeader().hide()

resize it after you populate it:

tw.resizeRowsToContents()
tw.resizeColumnsToContents() 

and then set size for dialog like this:

dialogWidth = tw.horizontalHeader().length() + 24
dialogHeight= tw.verticalHeader().length()   + 24
w.setFixedSize(dialogWidth, dialogHeight)

Dialog will automatically resize to the right size, no matter how much rows or columns you have, and what is inside of tableWidget cells

Upvotes: 2

Related Questions