PyQt:如何在QDialog中使小部件自动调整大小

10

当对话框的大小改变时,我很难使QDialog中的小部件自动调整大小。

在下面的程序中,如果你调整主窗口的大小,文本区域会自动调整大小。然而,在对话框内部的文本区域保持相同的大小。

有没有办法使对话框中的文本区域自动调整大小?我尝试在对话框本身和两个小部件上使用setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored),但似乎没有效果。

我正在使用Qt版本3.3.7和PyQt版本3.5.5-29,操作系统为openSuSE 10.2,如果这方面有所关联。

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()
4个回答

7

QMainWindow对于中央窗口部件有特殊的行为,而QDialog没有。要实现所需的行为,需要创建一个布局,将文本区域添加到布局中并将布局分配给对话框。


3

关于这个问题,我想补充一点说明- 我试图从一个应用程序中生成一个子窗口,该应用程序是一个QDialog,其中包含一个单独的QTextEdit作为子级/内容 - 我希望QTextEdit能够在QDialog窗口大小更改时自动调整大小。对于我来说,使用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_()

2

我之前尝试过使用QLayout,但没有成功。我试图做以下操作:

dialog.setLayout(some_layout)

但是我无法让这种方法生效,所以我放弃了。

我的错误在于我试图将布局传递给对话框,而应该将对话框传递给布局。

添加以下行:

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

TestDialog.__init__的结尾处添加可以解决问题。
感谢Monjardin提醒我重新考虑布局。

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接