英文:
set style for QWidgetItem PyQt
问题
我有一个名为self.box的布局,并且我想使用itemAt
方法选择这个布局的一个索引,并更改相关的样式,但是我遇到了这个错误:
'QWidgetItem'对象没有属性'setStyleSheet'
请注意,我知道我可以单独为每个按钮设置样式,但我想知道是否有一种方法可以为QWidgetItem设置样式。
代码:
from PyQt6.QtWidgets import *
from PyQt6.QtCore import *
from PyQt6.QtGui import *
class main(QMainWindow):
def __init__(self):
super().__init__()
self.box = QHBoxLayout()
self.widget = QWidget()
self.widget.setLayout(self.box)
self.button = QPushButton('button1')
self.button2 = QPushButton('button2')
self.button3 = QPushButton('button3')
self.box.addWidget(self.button)
self.box.addWidget(self.button2)
self.box.addWidget(self.button3)
self.box.itemAt(1).setStyleSheet('background-color:red;')
self.setCentralWidget(self.widget)
self.show()
app = QApplication([])
m = main()
m.show()
app.exec()
英文:
I have a layout named self.box
and I want to select one of the indexes of this layout with the itemAt
method
and change the related style
but i get this error:
'QWidgetItem' object has no attribute 'setStyleSheet'
Note that I know that I can style each of the buttons separately
But I want to know if there is a way to style the QWidgetItem
code:
from PyQt6.QtWidgets import *
from PyQt6.QtCore import *
from PyQt6.QtGui import *
class main(QMainWindow):
def __init__(self):
super().__init__()
self.box = QHBoxLayout()
self.widget = QWidget()
self.widget.setLayout(self.box)
self.button = QPushButton('button1')
self.button2 = QPushButton('button2')
self.button3 = QPushButton('button3')
self.box.addWidget(self.button)
self.box.addWidget(self.button2)
self.box.addWidget(self.button3)
self.box.itemAt(1).setStyleSheet('background-color:red;')
self.setCentralWidget(self.widget)
self.show()
app = QApplication([])
m = main()
m.show()
app.exec()
答案1
得分: 1
我找到答案了:
self.box.itemAt(1).widget().setStyleSheet('background-color:red')
英文:
I found the answer myself:
self.box.itemAt(1).widget().setStyleSheet('background-color:red')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论