I want to display a standard warning icon along with some description text in QLabel
in pyqt. Qlabel
doesn't have setIcon
function. So how could I do that?
Any help would be appreciated.
I know I'm a bit late to the party, but here's my solution to this problem:
import qtawesome as qta
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
class IconLabel(QWidget):
IconSize = QSize(16, 16)
HorizontalSpacing = 2
def __init__(self, qta_id, text, final_stretch=True):
super(QWidget, self).__init__()
layout = QHBoxLayout()
layout.setContentsMargins(0, 0, 0, 0)
self.setLayout(layout)
icon = QLabel()
icon.setPixmap(qta.icon(qta_id).pixmap(self.IconSize))
layout.addWidget(icon)
layout.addSpacing(self.HorizontalSpacing)
layout.addWidget(QLabel(text))
if final_stretch:
layout.addStretch()
I am using QtAwesome
to get the desired icon.
Now you can easily insert the icon label into your own PyQt5 layout. Example.
mylayout.addWidget(IconLabel("fa.scissors", "Slicer Limit:"))
What it looks like:
Note that I included an option final_stretch
. In a vertical layout, you'll want to keep final_stretch = True
for proper left-alignment (see image avove). In a horizontal layout (i.e., when placing multiple IconLabels
next to each other in the same row), however, you'll probably want to set final_stretch = False
in order to save space.
QLabel
doesn't have a setIcon
method, but it has setPixmap
. But if you use that to set a QPixmap
it overrides your text. but there are a few possibilities to achieve what you want:
QLabel
to display text+imageIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With