为PyQt的QWidgetItem设置样式。

huangapple go评论61阅读模式
英文:

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')

huangapple
  • 本文由 发表于 2023年7月11日 00:10:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76655540.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定