【问题标题】:QPushButton does not work when added to LayoutQPushButton 在添加到 Layout 时不起作用
【发布时间】:2020-02-06 11:01:25
【问题描述】:

我有一个 QWidget(它被设置为一个名为 Ui_Form 的 UI),我希望它成为 QFrame 的一部分,而 QFrame 已经是我的 QMainWindow 的一部分;这个 QWidget 是一个带有按钮和其他对象的 UI 表单。我尝试将其添加为框架布局的一部分,但问题是当我将 QWidget 添加到布局时,Ui_Form 中的 QPushButtons 停止工作,我的代码如下。

## My QMainWindow
from PyQt5 import QtCore, QtGui, QtWidgets

class MainWindow(object):
    def setupUi(self, mainWindow):
        # pyuic5 code here ...
        self.MyFrame = QtWidgets.QFrame(self.centralwidget)
        self.MyFrame.setGeometry(QtCore.QRect(0, 560, 1201, 201))
        self.MyFrame.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.MyFrame.setFrameShadow(QtWidgets.QFrame.Raised)
        #  more pyuic5 code here ...

        my_form = QtWidgets.QWidget()
        my_form_ui = Ui_Form()
        my_form_ui.setupUi(my_form)
        frame_layout = QtWidgets.QVBoxLayout()
        frame_layout.addWidget(my_form)
        self.MyFrame.setLayout(frame_layout)

我的 Ui_Form 类,在将其添加到布局之前可以正常工作

## My Ui_Form class
from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Form(object):
    def setupUi(self, form):
        # some pyuic5 code here ...
        self.myPushButton = QtWidgets.QPushButton(form)
        self.myPushButton.setGeometry(QtCore.QRect(415, 200, 101, 40))
        self.myPushButton.setObjectName("myPushButton")
        self.myPushButton.clicked.connect(self.printHello) 

    def printHello(self):
        print("Hello World!")

MainWindow 将很好地显示 Ui_Form 中的所有元素,但按钮确实工作,即使我调用 setupUi 方法将按钮连接到 printHello 方法。有任何想法吗?

【问题讨论】:

  • Camaron 你知道,如果你停止使用 Designer 并从头开始编写 PyQt 代码,你可以避免这些令人头疼的问题——从长远来看,这同样容易,也许更容易——大多数人我已经教过如何在没有设计器的情况下进行操作,甚至从未考虑过回顾,因为没有设计器就很容易做到,然后代码就像使用起来容易 10 倍,你完全理解它在做什么而不是做而不是一些你不应该接触的神秘代码块
  • 感谢您的回复,但重写该部分可能需要更多时间
  • 好的,但从长远来看,只要知道在没有 Designer 的情况下编写它所花费的时间要比处理使用 Designer 必须应对的各种问题要少得多——进一步以后的维护也需要更长的时间——基本上是你什么时候开始节省时间而不是失去它。请不要误会我的意思 - 完全取决于你,只是想从曾经在那里做过那种事情的人那里给你深思

标签: python python-3.x pyqt pyqt5 qt-designer


【解决方案1】:

解释:

问题是my_form_ui是一个局部变量,当你执行完setupUi()方法时会被消除,所以printHello()方法将不再存在。使用QPushButton 不会产生该问题,因为所有权是 GUI。

解决办法:

my_form_ui设置为类的属性:

# ...
my_form = QtWidgets.QWidget()
self.my_form_ui = Ui_Form()
self.my_form_ui.setupUi(my_form)
frame_layout = QtWidgets.QVBoxLayout()
# ...

【讨论】:

    猜你喜欢
    • 2019-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-02
    • 1970-01-01
    • 2018-04-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多