كيف أحصل على بعض الفتحات / الوظيفة ليتم تنفيذها عند فحص / QTableWidgetItem
-
26-09-2019 - |
سؤال
لديّ جدول تم إنشاؤه ديناميكيًا ، يحتوي على صفوف N و M QTableWidgetItems (التي يتم استخدامها فقط كمربعات اختيار) لكل صف - أحتاج إلى تشغيل رمز يعرف الصف والعمود كلما تم فحص خانة الاختيار أو عدم تحديدها.
تشبه الفئة الفرعية مربع الاختيار:
class CheckBox(QTableWidgetItem):
def __init__(self):
QTableWidgetItem.__init__(self,1000)
self.setTextAlignment(Qt.AlignVCenter | Qt.AlignJustify)
self.setFlags(Qt.ItemFlags(
Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled ))
def stateChanged(self):
do_something(self.row(),self.column())
...
من الواضح أن هذا لا يعيد تعريف الوظيفة التي يتم استدعاؤها عندما SIGNAL('stateChanged(int)')
-يحدث شيء ، لأنه ، حسنًا ، لا يحدث شيء.
ولكن ، إذا فعلت:
item = CheckBox()
self.connect(item, SIGNAL('stateChanged(int)'), item.stateChanged)
في الحلقة ، قم بإنشاء الجدول ، أحصل على خطأ:
TypeError: arguments did not match any overloaded call:
QObject.connect(QObject, SIGNAL(), QObject, SLOT(), Qt.ConnectionType=Qt.AutoConnection): argument 1 has unexpected type 'CheckBox'
QObject.connect(QObject, SIGNAL(), callable, Qt.ConnectionType=Qt.AutoConnection): argument 1 has unexpected type 'CheckBox'
QObject.connect(QObject, SIGNAL(), SLOT(), Qt.ConnectionType=Qt.AutoConnection): argument 1 has unexpected type 'CheckBox
تعديل: لقد حاولت أيضًا إعادة تعريف setCheckState()
ولكن يبدو أن هذا يفعل ليس احصل على استدعاء عندما يتم فحص العنصر أو عدم التحقق منه.
تحرير 2: علاوة على ذلك ، تغيير الاتصال
self.connect(self.table, SIGNAL('itemClicked(item)'),
self.table.stateChanged)
أين table = QTableWidget()
لا يساعد أيضًا.
كيف أفعل هذا بالطريقة الصحيحة؟
المحلول
أبسط حل هو على الأرجح الاتصال بـ cellChanged(int, int)
إشارة QTableWidget
; ؛ ألقِ نظرة على المثال التالي:
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
#signal handler
def myCellChanged(row, col):
print row, col
#just a helper function to setup the table
def createCheckItem(table, row, col):
check = QTableWidgetItem("Test")
check.setCheckState(Qt.Checked)
table.setItem(row,col,check)
app = QApplication(sys.argv)
#create the 5x5 table...
table = QTableWidget(5,5)
map(lambda (row,col): createCheckItem(table, row, col),
[(row, col) for row in range(0, 5) for col in range(0, 5)])
table.show()
#...and connect our signal handler to the cellChanged(int, int) signal
QObject.connect(table, SIGNAL("cellChanged(int, int)"), myCellChanged)
app.exec_()
يخلق جدول 5x5 من مربعات الاختيار. كلما تم فحص/لم يتم التحقق من أحدهم ، myCellChanged
يتم استدعاؤه ويطبع الصف وعمود مربع الاختيار الذي تم تغييره ؛ يمكنك بالطبع الاستخدام QTableWidget.item(someRow, someColumn).checkState()
لمعرفة ما إذا كان قد تم فحصه أو دون رادع.