首页 > 解决方案 > PyQt5:如何在 QMessageBox 中显示列表?类型错误:参数 3 具有意外类型“列表”

问题描述

我正在尝试在 QMessageBox 中显示一个列表,但我不断收到错误消息:

TypeError: question(QWidget, str, str, buttons: Union[QMessageBox.StandardButtons, QMessageBox.StandardButton] = QMessageBox.StandardButtons(QMessageBox.Yes|QMessageBox.No), defaultButton: QMessageBox.StandardButton = QMessageBox.NoButton): 参数 3 有意外类型“列表”

这是代码:

import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QPushButton, QAction, QLineEdit, QMessageBox
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot

class App(QMainWindow):

    def __init__(self):
        super().__init__()
        self.title = 'List manipulation'
        self.left = 10
        self.top = 10
        self.width = 325
        self.height = 300
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        # Create textbox
        self.textbox = QLineEdit(self)
        self.textbox.move(20, 20)
        self.textbox.resize(280, 200)

        # Create a button in the window
        self.button = QPushButton('Show text', self)
        self.button.move(20, 230)

        # connect button to function on_click
        self.button.clicked.connect(self.on_click)
        self.show()

    @pyqtSlot()
    def on_click(self):
        textboxValue = self.textbox.text()
        xlist = textboxValue.splitlines()
        xlist_final=[]
        for xitem in xlist:
            if xitem.find("abc") != -1:
                xlist_final.append(xitem)
    QMessageBox.question(self, 'List manipulation', xlist_final, QMessageBox.Ok, QMessageBox.Ok)
    self.textbox.setText("")


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())

在此处输入图像描述 框上的输入是这些行:

abc
xabcx
def
zabc
ghi
ooabc
abccc

我想过滤上面的列表以仅显示包含“abc”的单词,结果将是:

abc
xabcx
zabc
ooabc
abccc

我已经在上面的python文件中写了代码如下

textboxValue = self.textbox.text()
            xlist = textboxValue.splitlines()
            xlist_final=[]
            for xitem in xlist:
                if xitem.find("abc") != -1:
                    xlist_final.append(xitem)

问题是如何在 Qmessagebox 上显示以包含列表,谢谢您的帮助

标签: pythonpython-3.xpyqtpyqt5qmessagebox

解决方案


\n一种可能的解决方案是使用 using连接字符串,join()如下所示:

@pyqtSlot()
def on_click(self):
    textboxValue = self.textbox.text()
    xlist = textboxValue.splitlines()
    xlist_final = [xitem for xitem in xlist if xitem.find("abc") != -1]
    QMessageBox.question(self, 'List manipulation', "\n".join(xlist_final), QMessageBox.Ok, QMessageBox.Ok)
    self.textbox.clear()

在此处输入图像描述


推荐阅读