PyQt: getting widgets to resize automatically in a QDialog

痴心易碎 提交于 2019-11-27 23:56:01

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.

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.

Just to add a little note about this - I was trying to have a child window spawned from an application, which is a QDialog, containing a single QTextEdit as a child/content - and I wanted the QTextEdit to resize automatically whenever the QDialog window size changes. This seems to have done the trick for me with PyQt4:

def showTextWindow(self):

  #QVBox, QHBox # don't exist in Qt4

  dialog = QDialog(self)
  #dialog.setGeometry(QRect(100, 100, 400, 200))
  dialog.setWindowTitle("Title")
  dialog.setAttribute(QtCore.Qt.WA_DeleteOnClose)

  textbox = QTextEdit(dialog)
  textbox.setReadOnly(True)
  textbox.setMinimumSize(QSize(400, 400*0.75))
  textbox.setText("AHAAA!")

  # this seems enough to have the QTextEdit 
  # autoresize to window size changes of dialog!
  layout = QHBoxLayout(dialog)
  layout.addWidget(textbox)
  dialog.setLayout(layout)

  dialog.exec_()

Check out Python QT Automatic Widget Resizer It's suppose to work well.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!