我想创建一个QPushButton并保持按下状态,直到用户再次按下它为止。我知道我可以为此使用setCheckable。但我不确定如何为按钮更改状态(按下和未按下)时触发的按钮创建适当的信号。切换似乎有效,但它正在发送3个参数。我不确定示例中要发送的3个参数是什么。
import maya.cmds as cmds
import os
import maya.OpenMayaUI as mui
from PySide2 import QtWidgets,QtCore,QtGui
import shiboken2
class widget():
def __init__(self):
self.objs = ["box_1","box_2","box_3"]
def label_event(self,text):
print("this is the pressed button's label", text)
def populate(self):
for obj in self.objs:
label = QtWidgets.QPushButton(obj)
label.setCheckable(True)
label.toggled.connect(partial(self.label_event, obj))
self.vertical_layout_main.addWidget(label)
def palette_ui(self):
windowName = "palette"
if cmds.window(windowName,exists = True):
cmds.deleteUI(windowName, wnd = True)
pointer = mui.MQtUtil.mainWindow()
parent = shiboken2.wrapInstance(long(pointer),QtWidgets.QWidget)
self.window = QtWidgets.QMainWindow(parent)
self.window.setObjectName(windowName)
self.window.setWindowTitle(windowName)
self.mainWidget = QtWidgets.QWidget()
self.window.setCentralWidget(self.mainWidget)
self.vertical_layout_main = QtWidgets.QVBoxLayout(self.mainWidget)
self.populate()
self.window.setAttribute(QtCore.Qt.WA_DeleteOnClose)
self.window.show()
lg = widget()
lg.palette_ui()
答案 0 :(得分:2)
您必须使用setCheckable(True)
激活属性并使用toggled
信号:
import sys
from PySide import QtGui
def function(checked):
print("is checked?: ", checked)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
button = QtGui.QPushButton("press me")
button.setCheckable(True)
button.toggled.connect(function)
button.show()
sys.exit(app.exec_())
更新:
请勿使用object是保留字,另一方面,信号会传递所检查的参数,如果要传递另一个参数,还必须将其放在函数中:
def label_event(self, text, checked): # <---
print("this is the pressed button's label", text, checked)
def populate(self):
for obj in self.objects:
label = QtWidgets.QPushButton(obj)
label.setCheckable(True)
label.toggled.connect(partial(self.label_event, obj))
self.vertical_layout_main.addWidget(label)