当前位置:网站首页>[pyqt] the cellwidget in tablewidget uses signal and slot mechanism

[pyqt] the cellwidget in tablewidget uses signal and slot mechanism

2022-07-07 10:59:00 __ Watson__

demand

Need to be in tableWidget Inside cellWidget( For example, the QComboBox and QCheckBox) Respond to the operation of , This response will act on others cellWidget
 Insert picture description here

before this , I wanted to pass QTableWidget Signal to achieve , But I tested it ,cellWidget The following signals cannot be sent , Unable to meet the above requirements .
 Insert picture description here

Solution

  1. In the use of setCellWIdget When adding anonymous controls , Use .connect() Connect the anonymous control object to the corresponding slot function ;
  2. Because of adding cellWidget when , Control is an anonymous object , In order to facilitate subsequent recognition and operation , Use dictionary as registration , Bind the object to the row index ;
  3. In the slot function Use self.sender(), Get the control object that sends this signal to trigger this slot function , Then get the row of the control through the registration dictionary , Then get other control objects on the row from the registration dictionary of the number of rows for operation .

Code example

  1. Create an anonymous control registration dictionary
self.cellWidgetRegistry1: Typing.Dict[QComboBox, int] = dict()
self.cellWidgetRegistry2: Typing.Dict[int, QCheckBox] = dict()
  1. add to cellWidget Control , And connect the slot function , And register anonymous control objects
def update_tableWidget(self):
	for row in range(12):
		cbb = QComboBox()  #  Create anonymous control objects 
		cbb.addItems(["1", "2", "3"])
		self.tableWIdget.setCellWidget(row, 1, cbb)  #  add to cellWidge
		cbb.currentIndexChanged.connect(self.on_cbb_currentIndexChanged)  #  Anonymous control connection slot function 
		self.cellWidgetRegistry1[cbb] = row  #  Register to dictionary   Bind objects and rows 

		ckb = QCheckBox()
		self.tableWIdget.setCellWidget(row, 2, ckb)  #  add to cellWidge
		self.cellWidgetRegistry2[row] = ckb #  Register to dictionary   Bind rows and objects 
  1. Slot function gets the sender
@QtCore.pyqtSlot(int)
def on_cbb_currentIndexChanged(self, idx):
	cbb = self.sender()  #  Get the sender of this signal ( The control object )
	row = self.cellWidgetRegistry1.get(cbb, 0)
	#  By line number and another registration dictionary   Find other controls in the row in reverse 
	cbb2 = self.cellWidgetRegistry2.get(row, QCheckBox)
	...

Reference resources

【1】 pyqt Signal slot Judge the sender (sender
【2】QTableWidget About China cellWidget Signal processing method

Other options

You can try to use setItemDelegate agent ,

原网站

版权声明
本文为[__ Watson__]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207070846222286.html