views:

1915

answers:

2

I'm having difficulty getting widgets in a QDialog resized automatically when the dialog itself is resized.

In the following program, the textarea resizes automatically if you resize the main window. However, the textarea within the dialog stays the same size when the dialog is resized.

Is there any way of making the textarea in the dialog resize automatically? I've tried using setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) on the dialog itself and the two widgets within, but that seems to have no effect.

I'm using Qt version 3.3.7 and PyQt version 3.5.5-29 on openSuSE 10.2, if that's relevant.

import sys
from qt import *

# The numbers 1 to 1000 as a string.
NUMBERS = ("%d " * 1000) % (tuple(range(1,1001)))

# Add a textarea containing the numbers 1 to 1000 to the given
# QWidget.
def addTextArea(parent, size):
    textbox = QTextEdit(parent)
    textbox.setReadOnly(True)
    textbox.setMinimumSize(QSize(size, size*0.75))
    textbox.setText(NUMBERS)


class TestDialog(QDialog):
    def __init__(self,parent=None):
        QDialog.__init__(self,parent)
        self.setCaption("Dialog")
        everything = QVBox(self)

        addTextArea(everything, 400)
        everything.resize(everything.sizeHint())


class TestMainWindow(QMainWindow):
    def __init__(self,parent=None):
        QMainWindow.__init__(self,parent)
        self.setCaption("Main Window")
        everything = QVBox(self)

        addTextArea(everything, 800)

        button = QPushButton("Open dialog", everything)
        self.connect(button, SIGNAL('clicked()'), self.openDialog)        

        self.setCentralWidget(everything)
        self.resize(self.sizeHint())

        self.dialog = TestDialog(self)

    def openDialog(self):
        self.dialog.show()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainwin = TestMainWindow(None)
    app.setMainWidget(mainwin)
    mainwin.show()
    app.exec_loop()
+1  A: 

QMainWindow has special behavior for the central widget that a QDialog does not. To achieve the desired behavior you need to create a layout, add the text area to the layout and assign the layout to the dialog.

Judge Maygarden
+1  A: 

I had looked at using a QLayout before but had no luck. I was trying to do something like

dialog.setLayout(some_layout)

but I couldn't get that approach to work so I gave up.

My mistake was that I was trying to pass the layout to the dialog when I should have been passing the dialog to the layout.

Adding the lines

layout = QVBoxLayout(self)
layout.add(everything)

to the end of TestDialog.__init__ fixes the problem.

Thanks to Monjardin for prompting me to reconsider layouts.

Pourquoi Litytestdata