1

I like the idea of using the loadUi() method in PyQt to load in a QtDesigner interface file as I'm often changing the ui file and don't want to be constantly converting it to a py file.

However, I've been having difficulty understanding how to access the different widgets and views in my ui file. The below shows how I'm loading in the ui:

class MyClass(QtGui.QMainWindow):
    def __init__(self, parent = None):
        super().__init__(parent)
        ui = uic.loadUi('MyUserInterface.ui',self)


if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    mainapplication = MyClass()
    mainapplication.show()
    app.exec_()

It displays fine, but I was expecting that I would be able to access the elements of the GUI by something along the lines of...

ui.sampleButton.makeDraggable()

My question is, how can I access the various elements within my GUI?

Edit 1: I Also have tried to without assigning the uic.load call to ui. When accessing as shown below, I can access some of the properties through using Ui_MainWindow. However, it throws an error

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    mainapplication = MyClass()
    mainapplication.Ui_MainWindow.graphicsView.acceptDrops(True)
    mainapplication.show()
    app.exec_()

The error i get is...

Traceback (most recent call last):  File "C:\Users\Me\workspaces\com.samplesoftware.software\src\SoftwareView\MyClass.py", line 17, in <module>
  mainapplication.Ui_MainWindow.graphicsView.acceptDrops(True)
  AttributeError: 'MyClass' object has no attribute 'Ui_MainWindow'

Any ideas?

4

3 回答 3

0

您不需要将其转换为 .py 文件,但您必须为它们命名才能访问它们,否则您需要知道在 ui 文件中调用的 sampleButton 是什么。

您可以简单地将 sampleButton 重命名为 my_btn 并访问它。

于 2012-12-05T11:10:00.870 回答
0

我发现原因是因为我试图在运行 app.exec_() 之前调用 Ui_MainWindow。将 Ui_MainWindow 调用移到末尾后,它确实可以工作。我猜,事后看来,MainWindow 需要存在才能改变它的属性。

于 2012-12-06T05:18:44.783 回答
0

loadUi函数ui 文件路径作为第一个参数,将基本实例作为第二个参数。

基实例应该是与 UI 中的顶级小部件相同的 Qt 类。这是因为loadUi会将所有 UI 插入到基本实例中,并且可能需要在此过程中调用它的一些方法。UI 中定义的所有子小部件最终都将作为基本实例的属性。

所以你应该loadUi在你的__init__

class MyClass(QtGui.QMainWindow):
    def __init__(self, parent = None):
        super(MyClass, self).__init__(parent)
        uic.loadUi('MyUserInterface.ui', self)

然后你应该能够graphicsView像这样访问:

        self.graphicsView.setAcceptDrops(True)
于 2012-12-05T19:46:48.917 回答