问题
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