PyQt5对话框窗口打开时没有布局

时间:2017-12-17 23:13:40

标签: layout dialog pyqt5 python-3.6

当我从主窗口(QMainWindow)中加载一个对话框(QMainWindow)窗口时,即使调用了setupUi()函数,它也会在没有布局的情况下加载。

以下是重要的代码段,click here用于完整代码的pastebin链接

StackTrace:
at Microsoft.VisualBasic.CompilerServices.Symbols.Container.GetMembers  (String& MemberName, Boolean ReportErrors)
at Microsoft.VisualBasic.CompilerServices.NewLateBinding.ObjectLateGet(Object Instance, Type Type, String MemberName, Object[] Arguments, String[] ArgumentNames, Type[] TypeArguments, Boolean[] CopyBack)
at Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet(Object Instance, Type Type, String MemberName, Object[] Arguments, String[] ArgumentNames, Type[] TypeArguments, Boolean[] CopyBack)
at HOAManagerClient051.MultiViolations_Page._Closure$__13-0._Lambda$__4() in C:\Path\HOAManagerClient051\HOAManagerClient051\Pages\Board\Violations\MultiViolations_Page.xaml.vb:line 822
at System.Threading.Tasks.Task.InnerInvoke()
at System.Threading.Tasks.Task.Execute()

现在我的对话框看起来像这样:

对话框布局失败

当我自己从自己创建的脚本加载对话框时:

class Ui_Dialog(QMainWindow):
    def __init__(self, parent=None):
        super(Ui_Dialog, self).__init__(parent)
        self.setupUi(self)
    def setupUi(self, Dialog):
        ...

class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi(self)
        self.show()
        ....
    def setupUi(self, Form):
        ...
        self.auto_sap_btn = QPushButton(Form)
        self.auto_sap_btn.setGeometry(QRect(0, 0, 61, 25))
        self.auto_sap_btn.setObjectName('auto_sap_btn')
        self.auto_sap_btn.clicked.connect(self.openDialog)

    def openDialog(self):
        self.window = Ui_Dialog(self)
        self.window.setupUi(self.window)
        self.window.move(600, 500)
        self.window.show()

它看起来像这样:

正确的对话框布局

我错过了什么?

1 个答案:

答案 0 :(得分:1)

当您在Qt Designer中基于模板创建设计时,当您必须传递相应的小部件时,当您创建Ui_Dialog时,您肯定使用了Dialog with Buttons Right所以在这种情况下您应该使用QDialog而不是QMainWindow :

class Ui_Dialog(QDialog): # change QMainWindow to QDialog
    def __init__(self, parent=None):
        super(Ui_Dialog, self).__init__(parent)
        self.setupUi(self)
        [...]

另一个错误是第二次使用setupUi()方法,因为此方法负责填充窗口小部件,通过调用它2次,您将不必要地添加更多窗口小部件:

def openDialog(self):
    self.window = Ui_Dialog(self)
    self.window.move(600, 500)
    self.window.show()