我已经编写了以下代码:
使用上述代码,我成功地创建了可勾选的框。但是当用户勾选某个项目时,我希望在运行程序时打印出已勾选的项目。据我所知,我需要使用一个事件或信号,但我不确定如何设置信号。我找到了一个示例代码,展示了使用MousePressEvent的用法,但我不确定如何使用Python实现该代码。
from PyQt4 import QtCore, QtGui
import sys
class window(QtGui.QMainWindow):
def __init__(self, parent=None):
super(window, self).__init__(parent)
self.TreeWidget = QtGui.QTreeWidget()
self.TreeWidget.setColumnCount(1)
item1 = QtGui.QTreeWidgetItem(["Item 1"])
item1.setCheckState(0, QtCore.Qt.Checked)
item2 = QtGui.QTreeWidgetItem(["Item 2"])
item2.setCheckState(0, QtCore.Qt.Unchecked)
item3 = QtGui.QTreeWidgetItem(["Item 3"])
item3.setCheckState(0, QtCore.Qt.Unchecked)
self.TreeWidget.addTopLevelItem(item1)
self.TreeWidget.addTopLevelItem(item2)
self.TreeWidget.addTopLevelItem(item3)
self.setCentralWidget(self.TreeWidget)
if item1.checkState(0) == QtCore.Qt.Checked:
print('item 1 is checked')
if item2.checkState(0) == QtCore.Qt.Checked:
print('item 2 is checked')
if item3.checkState(0) == QtCore.Qt.Checked:
print('item 3 is checked')
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
ui = window()
ui.show()
sys.exit(app.exec_())
使用上述代码,我成功地创建了可勾选的框。但是当用户勾选某个项目时,我希望在运行程序时打印出已勾选的项目。据我所知,我需要使用一个事件或信号,但我不确定如何设置信号。我找到了一个示例代码,展示了使用MousePressEvent的用法,但我不确定如何使用Python实现该代码。
#include <QtGui>
class TreeWidget : public QTreeWidget
{
public:
TreeWidget()
{
setColumnCount(1);
item1 = new QTreeWidgetItem(this);
item1->setExpanded(true);
item1->setFlags(item1->flags() | Qt::ItemIsUserCheckable);
item1->setCheckState(0, Qt::Checked);
item1->setText(0, "item 1");
item2 = new QTreeWidgetItem(item1);
item2->setFlags(item2->flags() | Qt::ItemIsUserCheckable);
item2->setCheckState(0, Qt::Checked);
item2->setText(0, "item 2");
item3 = new QTreeWidgetItem(this);
item3->setText(0, "item 3");
item3->setFlags(item3->flags() | Qt::ItemIsUserCheckable);
item3->setCheckState(0, Qt::Checked);
}
void mousePressEvent(QMouseEvent *event)
{
QModelIndex indexClicked = indexAt(event->pos());
if(indexClicked.isValid()) {
QRect vrect = visualRect(indexClicked);
int itemIndentation = vrect.x() - visualRect(rootIndex()).x();
QRect rect = QRect(header()->sectionViewportPosition(0) + itemIndentation
, vrect.y(), style()->pixelMetric(QStyle::PM_IndicatorWidth), vrect.height());
if(rect.contains(event->pos())) {
qDebug() << "checkbox clicked";
QTreeWidget::mousePressEvent(event);
return;
} else {
QTreeWidget::mousePressEvent(event);
}}}
private:
QTreeWidgetItem *item1;
QTreeWidgetItem *item2;
QTreeWidgetItem *item3;
QTreeWidgetItem *item4;
};
int main(int argc, char **argv)
{
QApplication app(argc, argv);
TreeWidget box;
box.show();
return app.exec();
}