QListViewItem 只能用于 QListView 控件中,而 QTree 控件需要使用 QTreeWidgetItem。因此,如果你想让自定义控件成为 QTree 的子项,你需要继承 QTreeWidgetItem 并实现自己的子类。
首先,创建一个新的类,例如 CustomTreeWidgetItem,继承自 QTreeWidgetItem:
class CustomTreeWidgetItem : public QTreeWidgetItem
{
public:
CustomTreeWidgetItem(QTreeWidget *parent);
CustomTreeWidgetItem(QTreeWidgetItem *parent);
CustomTreeWidgetItem(QTreeWidget *parent, const QStringList &strings);
CustomTreeWidgetItem(QTreeWidgetItem *parent, const QStringList &strings);
private:
// add your custom controls and properties here
};
然后,在 CustomTreeWidgetItem 类中添加你想要的自定义控件和属性,例如:
class CustomTreeWidgetItem : public QTreeWidgetItem
{
public:
CustomTreeWidgetItem(QTreeWidget *parent);
CustomTreeWidgetItem(QTreeWidgetItem *parent);
CustomTreeWidgetItem(QTreeWidget *parent, const QStringList &strings);
CustomTreeWidgetItem(QTreeWidgetItem *parent, const QStringList &strings);
private:
QLabel *m_label;
QPushButton *m_button;
public:
QLabel *label() const { return m_label; }
void setLabel(QLabel *label) { m_label = label; }
QPushButton *button() const { return m_button; }
void setButton(QPushButton *button) { m_button = button; }
};
接下来,在 CustomTreeWidgetItem 构造函数中初始化你的自定义控件和属性:
CustomTreeWidgetItem::CustomTreeWidgetItem(QTreeWidget *parent)
: QTreeWidgetItem(parent)
{
m_label = new QLabel(this);
m_button = new QPushButton(this);
setText(0, "Custom Item");
setFlags(flags() | Qt::ItemIsEditable);
}
最后,在 QTree 控件中创建和添加 CustomTreeWidgetItem,例如:
QTreeWidget *treeWidget = new QTreeWidget(this);
CustomTreeWidgetItem *item = new CustomTreeWidgetItem(treeWidget);
item->setLabel(new QLabel("My Label", item));
item->setButton(new QPushButton("My Button", item));
treeWidget->addTopLevelItem(item);
现在,你已经成功地将自定义控件作为 QTree 的子项。