我使用多个 QTreeWidgetItem 创建了 QTreeWidget 。
这是我的代码:
//Defined property tree
m_pPropertyTree = new QTreeWidget();
m_pPropertyTree->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
m_pPropertyTree->setColumnCount(2);
m_pPropertyTree->setHeaderLabels(QStringList() << "Property" << "Value");
//Update to property tree
//--geometry
QTreeWidgetItem *pGeometryItem = new QTreeWidgetItem(m_pPropertyTree);
pGeometryItem->setText(0, "geometry");
//X
QTreeWidgetItem *pXItem = new QTreeWidgetItem();
pXItem->setText(0, "X");
pXItem->setText(1, QString::number(geometry().x()));
pXItem->setFlags(pXItem->flags() | Qt::ItemIsEditable);
pGeometryItem->addChild(pXItem);
//Y
QTreeWidgetItem *pYItem = new QTreeWidgetItem();
pYItem->setText(0, "Y");
pYItem->setText(1, QString::number(geometry().y()));
pYItem->setFlags(pYItem->flags() | Qt::ItemIsEditable);
pGeometryItem->addChild(pYItem);
//Width
QTreeWidgetItem *pWidthItem = new QTreeWidgetItem();
pWidthItem->setText(0, "Width");
pWidthItem->setText(1, QString::number(geometry().width()));
pWidthItem->setFlags(pWidthItem->flags() | Qt::ItemIsEditable);
pGeometryItem->addChild(pWidthItem);
//Height
QTreeWidgetItem *pHeightItem = new QTreeWidgetItem();
pHeightItem->setText(0, "Height");
pHeightItem->setText(1, QString::number(geometry().height()));
pHeightItem->setFlags(pHeightItem->flags() | Qt::ItemIsEditable);
pGeometryItem->addChild(pHeightItem);
双击某个项目时,我可以编辑该项目的文本。但是,我想只允许用户在编辑时输入数字。反正有吗?
答案 0 :(得分:1)
我认为有很多方法,但QItemDelegate::createEditor的重载比其他方法更有用。
您应该使用QValidator
编写代码,在您的情况下,请使用QIntValidator
。
class CustomDelegate : public QItemDelegate
{
public:
QWidget* createEditor(QWidget *parent, const QStyleOptionViewItem & option,
const QModelIndex & index) const
{
QLineEdit *lineEdit = new QLineEdit(parent);
// Set your validator, such as 'only number between 0 ~ 9 )
QIntValidator *validator = new QIntValidator(0, 9, lineEdit);
lineEdit->setValidator(validator);
return lineEdit;
}
};
然后,将自定义委托设置为树。
m_pPropertyTree->setItemDelegate( new CustomDelegate );