请帮我写一个Pyside2 QPushbutton的图标出现在文字上方的代码
时间: 2024-05-14 11:16:52 浏览: 12
好的,这是您要求的代码:
```
from PySide2.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout
from PySide2.QtGui import QIcon
app = QApplication([])
window = QWidget()
button = QPushButton('Click Me!')
button.setIcon(QIcon('icon.png'))
button.setIconSize(button.sizeHint().height() - 10)
button.setStyleSheet("QPushButton::hover{background-color: #8f8f8f;}")
layout = QVBoxLayout()
layout.addWidget(button)
window.setLayout(layout)
window.show()
app.exec_()
```
这段代码利用 PySide2 库创建了一个简单的 GUI 窗口,并在窗口中添加了一个文字和图标都显示的按钮,其中图标出现在文字上方。 请注意,将 icon.png 替换为您想要显示的图像文件。另外,当鼠标悬停在按钮上时,按钮的背景颜色将变为灰色。
相关问题
请帮我写一个Pyside2 QPushbutton的图标位于按钮文字上方的代码
可以参考以下代码:
```python
import sys
from PySide2.QtWidgets import QApplication, QWidget, QPushButton
from PySide2.QtGui import QIcon
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
# 创建一个按钮
btn = QPushButton('Button', self)
# 设置按钮上方的图标
icon = QIcon('icon.png')
btn.setIcon(icon)
btn.setIconSize(icon.actualSize(QSize(32, 32)))
# 设置按钮文字和图标的对齐方式
btn.setStyleSheet('QPushButton {text-align: center; padding: 15px;}'
'QPushButton::indicator {subcontrol-origin: padding; subcontrol-position: top center;}')
self.setGeometry(300, 300, 300, 200)
self.setWindowTitle('Icon on top of button')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
```
在这个例子中,我们首先创建了一个QPushButton对象(btn)。我们设置了按钮上方的图标,并使用setIconSize()方法设置图标的大小。然后,我们使用setStyleSheet()方法为按钮设置样式表。在样式表中,我们设置按钮上下文的位置为顶部中心,以使图标出现在按钮的顶部。最后,我们显示了QWidget对象。
请帮我写一个pyside2 更改QTableWidget某行颜色的代码
这里是一个示例代码,用于更改QTableWidget中第1行的背景颜色为红色:
```python
from PySide2.QtGui import QColor
from PySide2.QtWidgets import QApplication, QTableWidget, QTableWidgetItem
app = QApplication([])
table = QTableWidget()
table.setRowCount(3)
table.setColumnCount(2)
table.setItem(0, 0, QTableWidgetItem("A"))
table.setItem(0, 1, QTableWidgetItem("B"))
table.setItem(1, 0, QTableWidgetItem("C"))
table.setItem(1, 1, QTableWidgetItem("D"))
table.setItem(2, 0, QTableWidgetItem("E"))
table.setItem(2, 1, QTableWidgetItem("F"))
# 设置第1行的背景颜色为红色
for j in range(table.columnCount()):
item = table.item(0, j)
item.setBackground(QColor("red"))
table.show()
app.exec_()
```