【问题标题】:Convert QstringList to Qstring in PyQt在 PyQt 中将 QstringList 转换为 Qstring
【发布时间】:2016-04-06 09:46:05
【问题描述】:

我正在尝试使用 QFileDialog 获取文件名列表,并希望在 QLineEdit 中显示(在 Python 2.7 中)。

self.resLine = QLineEdit()
xxres_file = (QFileDialog.getOpenFileNames(self, 'Select File', '', '*.txt'))
self.resLine.setText(xxres_file)

它期望(如错误所示)一个 QString:

TypeError: QLineEdit.setText(QString): argument 1 has unexpected type 'QStringList'

有人可以帮我将 QStringList 转换为 QString。

提前致谢

【问题讨论】:

    标签: python pyqt qstring


    【解决方案1】:

    您想要的值是QStringList 中的字符串而不是列表本身

    你可以使用 QStringList.join 方法将列表中的元素连接在一起,然后对其调用 split 来得到一个原生 python 列表

    strlist = xxres_file.join(",") # this returns a string of all the elements in the QStringList separated by comma's
    
    strlist = strlist.split(",") # you can optionally split the string to get all the elements in a python list
    
    self.resLine.setText(strlist[0]) # your list contains only one string in this case
    

    在 python 3 中,QStringListQString 分别映射到原生 python 列表和字符串。

    【讨论】:

    • 感谢您的快速回复。不幸的是,当我选择多个文件时,这不起作用。仅使用 strlist = xxres_file.join(",")self.resLine.setText(strlist) 可以解决多个文件的问题。如果我错了,请纠正我
    • 是的,你是对的......它将QStringList 中的所有元素连接成一个字符串,由逗号分隔(或您指定的任何分隔符)。但是如果你出于其他原因想要单个元素,你可以在字符串上调用.split(),因为它现在是一个python字符串
    【解决方案2】:

    假设您使用的是相当新版本的 pyqt,您还可以告诉 pyqt 使用更新的 api 用于 qstrings

    import sip
    sip.setapi('QString', 2)
    
    # Do pyqt imports afterwards
    from PyQt4 import QtCore, QtGui
    

    然后您只需使用常规的strlist 方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-06
      • 1970-01-01
      • 1970-01-01
      • 2011-12-23
      • 2013-09-30
      • 2019-12-23
      • 2011-08-21
      • 2012-04-01
      相关资源
      最近更新 更多