我如何将图标放在pyqt5中的qpushbutton的文本之后?
图标不应在文本之前出现 - 它应该在文本之后或之下。目前看起来像这样:
但应该这样:轨道⨁
from PyQt5.QtWidgets import QApplication, QPushButton, QWidget, QVBoxLayout
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import Qt
import sys
app = QApplication(sys.argv)
window = QWidget()
layout = QVBoxLayout(window)
btn_add_track = QPushButton("Track")
btn_add_track.setIcon(QIcon("Icons/plus.png"))
layout.addWidget(btn_add_track)
window.show()
sys.exit(app.exec_())
QPushButton
。
引用此内容: -https://stackoverflow.com/a/47858386/10203327
QHBoxLayout
最简单的选项是更改按钮布局的方向:from PyQt5.QtWidgets import QApplication, QPushButton, QWidget, QVBoxLayout, QHBoxLayout, QLabel
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import Qt
import sys
app = QApplication(sys.argv)
window = QWidget()
layout = QVBoxLayout(window)
# Create a QWidget to hold the label and icon
btn_widget = QWidget()
btn_layout = QHBoxLayout(btn_widget)
btn_layout.setContentsMargins(0, 0, 0, 0) # Remove margins for better alignment
# Add the label and icon to the layout
label = QLabel("Track")
icon_label = QLabel()
icon_label.setPixmap(QIcon("Icons/plus.png").pixmap(16, 16)) # Set icon size
# Center-align the label and icon
btn_layout.addStretch() # Add stretch to push content to the center
btn_layout.addWidget(label, alignment=Qt.AlignCenter)
btn_layout.addWidget(icon_label, alignment=Qt.AlignCenter)
btn_layout.addStretch() # Add stretch to push content to the center
# Create a QPushButton and set the custom widget as its layout
btn_add_track = QPushButton()
btn_add_track.setLayout(btn_layout)
layout.addWidget(btn_add_track)
window.show()
sys.exit(app.exec_())
没有其他解决方案,这将保持原始按钮的外观,例如将图标文本和文本相对于按钮的居中(也可以使用其他解决方案完成,但需要更多代码)