如何连接到pyqt5中的不同类?

2024-04-25 01:18:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我想问一下如何连接两个不同的类。我在2个类中有以下代码(2个类是因为我创建了2个不同的接口)。1是QMainwindow,另一个是QWidget)。在

代码如下:

class MainWindow(QMainWindow, Ui_MainWindow):
    def open_inv_search_form(self):
            self.window = QtWidgets.QWidget()
            self.ui = Ui_Inv_Search()
            self.ui.setupUi(self.window)
            self.window.show()
            MainWindow.setEnabled(False)


class Inv_Search(QWidget, Ui_Inv_Search):    
    def __init__(self,):
            super(Inv_Search, self).__init__()

            self.btn_close_search.clicked.connect(self.close_inv_search_form)

    def close_inv_search_form(self):
            Inv_Search.hide()
            MainWindow.setEnabled(True)

其思想是当在主窗口中单击搜索按钮时,将弹出Inv_SEARCH,而主窗口将被禁用。这一部分我做得对。单击“关闭”按钮后,库存搜索将隐藏,主窗口将启用。然而,当单击“关闭”按钮时,什么都没有发生。完全没有错误。在

更新

我能成功地做我想做的事。这是我做的改变。让我知道这是好的还是可以更好。尽管如此,这个代码仍然有效。在

^{pr2}$

Tags: 代码selfformuiclosesearchdefwindow
2条回答

我假设某个地方有更多的代码和一个.ui文件。看起来像这条线

Inv_Search.hide()

应该改变

^{pr2}$

另外,我认为这是因为您需要调用实例上的方法,而不是类。在

self.ui = Ui_Inv_Search()

应该是的

self.ui = Inv_Search()

您正在使用MainWindow执行类似的操作。这里有点困难,因为您需要将MainWindow的实例存储在可访问的位置。虽然您可以通过^{}访问MainWindow实例,但在Python中,我更喜欢将实例传递给构造函数。所以

def __init__(self, mainWindow):
    self.mainWindow = mainWindow
    # ... all the other stuff too

作为您的Inv_Search构造函数,并且

self.ui = Inv_Search(self)
    # notice the new ^ argument

在您的MainWindow构造函数中。然后呢

self.mainWindow.setEnabled(True)

在你的课堂方法中。另外,您的参数签名对于clicked信号是错误的。使用

def close_inv_search_form(self, checked=None):
                    # Need this ^ argument, even if you don't use it.    

实际上,您尝试实现的功能似乎最适合于模式对话框,例如^{}提供的对话框,它将以本机方式处理我认为您正在寻找的许多效果。在

当您在close_inv_search_form中调用Inv_Search.hide()MainWindow.setEnabled(True)时,您需要在类本身上调用方法,而不是在实例上调用方法,这是您必须要做的。在

from PyQt5.QtCore import qApp

class MainWindow(QMainWindow, Ui_MainWindow):
    def open_inv_search_form(self):
            self.window = QtWidgets.QWidget()
            self.window.ui = Ui_Inv_Search()      # You have to set the attributes of the
            self.window.ui.setupUi(self.window)   # "window" not the instance of MainWindow
            self.window.show()
            self.setEnabled(False)

class Inv_Search(QWidget, Ui_Inv_Search):    
    def __init__(self,):
            super(Inv_Search, self).__init__()

            self.btn_close_search.clicked.connect(self.close_inv_search_form)

    def close_inv_search_form(self):
            self.hide()             # Use the method "hide" on the instance
            qApp.setEnabled(True)   # Use the method "setEnabled" on the instance

if __name__ == "__main__" :
    app = QApplication()
    main = MainWindow()   # This is the instance that can be referred to by qApp
    main.exec_()

相关问题 更多 >