【问题标题】:Passing variables into SLOTs - QSignalMapper将变量传递到 SLOT - QSignalMapper
【发布时间】:2014-08-12 14:16:59
【问题描述】:

我正在尝试对两个图像上传使用相同的图像上传功能。

所以在点击上传按钮时,我需要将 self.UploadStudentPhoto 或 self.UploadParentsPhoto 传递给 self.UploadFile() 函数,对应于按下的按钮。

由于我们无法将变量传递到 SLOT,所以我尝试使用 QSignalMapper,如下所示。

self.UploadStudentPhoto = QLineEdit() #Student Photo location
self.UploadParentsPhoto = QLineEdit() #Parents Photo location
self.ParentsImage = None

self.SignalMapper = QSignalMapper()
self.connect(self.ButtonUpload1,SIGNAL("clicked()"),self.SignalMapper, SLOT("map()"))
self.connect(self.ButtonUpload2,SIGNAL("clicked()"),self.SignalMapper,SLOT("map()"))

self.SignalMapper.setMapping(self.ButtonUpload1, self.UploadStudentPhoto)
self.SignalMapper.setMapping(self.ButtonUpload2, self.UploadParentsPhoto)

但我不确定需要将 SIGNAL("mapped()") 传递给我为文件上传编写的函数的以下行。我应该如何写下一行:

self.connect(self.SignalMapper,SIGNAL("mapped()"), self, self.UploadFile)

上传文件功能如下:

def UploadFile(self, ImagePath, ImageLabel):
    dir = os.path.dirname(".")
    formats = ["*.%s" % unicode(format).lower()\
        for format in QImageReader.supportedImageFormats()]
    self.fname = unicode(QFileDialog.getOpenFileName(self,"Image",dir,"Image (%s)" % " ".join(formats)))
    print self.fname
    ImagePath.setText(self.fname)
    ImagePath.selectAll()
    ImageLabel = QImage()
    ImageLabel.setPixmap(QPixmap.fromImage(ImageLabel))

我看到了很多 QSignalMapper 示例,但我不确定变量是如何传递的。 请提出建议。

【问题讨论】:

    标签: python qt python-2.7 qt4 pyqt4


    【解决方案1】:

    实际上,它可以通过在python中使用partial模块将变量传递给connect & SLOT;

    在我看来,我建议使用“简单”(我认为)来实现,我将在下面的代码中向您展示;

    from functools import partial
    .
    .
    .
            self.StudentPhoto = QLabel() # I know you have this.
            self.ParentsPhoto = QLabel() # I know you have this too.
            self.UploadStudentPhoto = QLineEdit()
            self.UploadParentsPhoto = QLineEdit()
            self.connect(self.ButtonUpload1, SIGNAL("clicked()"), partial(self.UploadFile, self.UploadStudentPhoto, self.StudentPhoto))
            self.connect(self.ButtonUpload2, SIGNAL("clicked()"), partial(self.UploadFile, self.UploadParentsPhoto, self.ParentsPhoto))
    .
    .
    .
        def UploadFile(self, ImagePath, ImageLabel):
            dir = os.path.dirname(".")
            formats = ["*.%s" % unicode(format).lower()\
                for format in QImageReader.supportedImageFormats()]
            self.fname = unicode(QFileDialog.getOpenFileName(self,"Image",dir,"Image (%s)" % " ".join(formats)))
            print self.fname
            ImagePath.setText(self.fname)
            ImagePath.selectAll()
    .
    .
    .
    

    示例参考:http://www.learnpython.org/en/Partial_functions

    官方参考:https://docs.python.org/2/library/functools.html


    问候,

    【讨论】:

      猜你喜欢
      • 2020-07-18
      • 1970-01-01
      • 2020-03-13
      • 2018-06-02
      • 2018-03-23
      • 2014-01-22
      • 2018-07-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多