简体   繁体   English

如何在qlistwidget pyqt4 python中添加带有文本的图像?

[英]how to add image with text in qlistwidget pyqt4 python?

How to add image/icon with text in a qlistwidget in pyqt4 python? 如何在pyqt4 python的qlistwidget中添加带有文本的图像/图标? I want to add an icon with text just like a chat system. 我想添加一个带有文本的图标,就像聊天系统一样。 thanks 谢谢

I have tried this right now and it works, supposing you have a file named tick.png in the same folder as this script. 我现在已经尝试过了,并且可以正常工作,假设您在与此脚本相同的文件夹中有一个名为tick.png的文件。

import sys
from PyQt4 import QtGui, QtCore
from PyQt4.QtGui import QApplication, QDialog, QListWidgetItem, QListWidget, QIcon

def main():

    app = QtGui.QApplication(sys.argv)
    window = QDialog()

    list = QListWidget( window )

    itm = QListWidgetItem( "Tick" );
    itm.setIcon(QIcon(r"tick.png"));
    list.addItem(itm);

    window.show( )
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

The chat-like-icon system may be different from this, but right now I don't see a way to have a QListWidgetItem with multiple smileys and text. 类似图标的聊天系统可能与此不同,但是现在我看不到拥有带有多个笑脸和文本的QListWidgetItem的方法。

You may think of smileys as a particular case of a QListWidgetItem where the text is blank and only the icon is present. 您可能会认为笑脸是QListWidgetItem的特殊情况,其中文本为空白,并且仅显示图标。

Another solution is using a read-only QTextEdit as chatboard and have the user typing its text + icon + text (etc.) in a separate editable QTextEdit. 另一种解决方案是使用只读QTextEdit作为聊天板,让用户在单独的可编辑QTextEdit中键入其文本+图标+文本(等)。 Then, when he presses the send button, append everything he typed to the read-only QTextEdit. 然后,当他按下发送按钮时,将他键入的所有内容附加到只读QTextEdit。

import sys
from PyQt4 import QtGui, QtCore
from PyQt4.QtGui import QApplication, QDialog, QListWidgetItem, QListWidget, QIcon, QTextEdit, QTextDocumentFragment

def main():

    app = QtGui.QApplication(sys.argv)
    window = QDialog()

    list = QListWidget( window )

    textEditor = QTextEdit( window );
    textEditor.setReadOnly( True )
    tick_icon = QTextDocumentFragment.fromHtml(r"<img src='tick.png'>");

    textEditor.insertPlainText ( " ValiumKnight writes: " )
    textEditor.textCursor().insertFragment(tick_icon);
    textEditor.insertPlainText ( " Hello World " )
    textEditor.textCursor().insertFragment(tick_icon);
    textEditor.textCursor().insertFragment(tick_icon);
    textEditor.textCursor().insertFragment(tick_icon);

    window.show( )
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

Bye! 再见!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM