How do I create a signal to open a QFileDialog in Qt Designer?

和自甴很熟 提交于 2019-12-20 02:43:25

问题


In Qt Designer 5, how do I create a signal to open a QFileDialog? I'm using Python and PyQt. I've tried creating signals with "Edit Signals/Slots" and I can select the button I want as sender, but I can't select an arbitrary function as the receiver, only existing widgets are available in the list.


回答1:


In order to create custom Signal/Slots to later use in your Python application you need to add them doing a right click on the widget and clicking on Change signals/slots..., as shown in the next image:

You'll need to add the desired slots, like shown here with the mybutton_clicked() function:

Thus far, the slots is created and it is possible to use it in the Signals & Slots Editor tab. Once in this tab, clicking in + button, the Receiver slot is present if the previous step is done right, as shown here:

Lastly, integrate the requested QFileDialog into the button press method, it is as easy as this :

from PyQt5.QtWidgets import QMainWindow, QApplication, QFileDialog
from PyQt5 import uic
import sys


form_class = uic.loadUiType("mainWindow.ui")[0]  # Load the UI

class MyWindowClass(QMainWindow, form_class):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.setupUi(self)

    def mybutton_clicked(self):
        options = QFileDialog.Options()
        fileName, _ = QFileDialog.getOpenFileName(self,"QFileDialog.getOpenFileName()", "","All Files (*)", options=options)
        if fileName:
            print(fileName)

app = QApplication(sys.argv)
myWindow = MyWindowClass(None)
myWindow.show()
app.exec_()


来源:https://stackoverflow.com/questions/42046092/how-do-i-create-a-signal-to-open-a-qfiledialog-in-qt-designer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!