有没有一种带有2个选项的按钮? 我想有一个按钮,其中选项1上的按钮将其颜色更改为红色,选项2上的颜色更改为黄色,选项3上的颜色更改为绿色。再次按(第4次)将从头开始(红色->黄色->绿色)。
到目前为止,我只能为2个选项设置按钮,但是我制作的destopapplication的用户应该具有3个选项。 到目前为止,这是我的代码(仅供参考:该按钮位于QTableWidget内,因此范围内为x):
for x in range(cell_num):
self.button = QPushButton(' ',self)
self.button.setFlat(True)
self.table.setCellWidget(x, 5, self.button) # lights_button
self.button.clicked.connect(
lambda state, w=self.table.cellWidget(x, 5), r=x, c=5: self.button_pushed(w, r, c)
)
def button_pushed(self, w, r, c):
if w.text() != " ":
w.setIcon(QIcon("..\image\green_button.png"))
w.setText(" ")
elif w.text() == "Likes/UnLikes/Normal":
w.setIcon(QIcon("..\image\yellow_button.png"))
w.setText(" Likes/Normal")
else:
w.setIcon(QIcon("..\image\darkred_button.png"))
w.setText(" ")
答案 0 :(得分:1)
您必须实现状态机,在这种情况下,最好创建一个自定义按钮。
from itertools import cycle
from PyQt5 import QtCore, QtGui, QtWidgets
class Button(QtWidgets.QPushButton):
RedState, YellowState, GreenState = range(3)
def __init__(self, *args, **kwargs):
super(Button, self).__init__(*args, **kwargs)
self._current_state = Button.RedState
self._states = cycle([Button.RedState, Button.YellowState, Button.GreenState])
self.on_clicked()
self.clicked.connect(self.on_clicked)
def update_button(self):
if self._current_state == Button.RedState:
self.setIcon(QtGui.QIcon(r"..\image\green_button.png"))
self.setText(" ")
elif self._current_state == Button.YellowState:
self.setIcon(QtGui.QIcon(r"..\image\yellow_button.png"))
self.setText(" Likes/Normal")
elif self._current_state == Button.GreenState:
self.setIcon(QtGui.QIcon(r"..\image\darkred_button.png"))
self.setText(" ")
@QtCore.pyqtSlot()
def on_clicked(self):
self._current_state = next(self._states)
self.update_button()
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.table = QtWidgets.QTableWidget(10, 10)
self.setCentralWidget(self.table)
for x in range(self.table.rowCount()):
button = Button(flat=True)
self.table.setCellWidget(x, 5, button)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())