QtTreePropertyBrowser 用法示例

创建 QtTreePropertyBrowser 实例

过程很简单。先创建 QDockWidget,再创建 QtTreePropertyBrowser,最后把 QtTreePropertyBrowser 对象放到 QDockWidget 对象中。

    QDockWidget *dock = new QDockWidget(this);
    addDockWidget(Qt::RightDockWidgetArea, dock);
    propertyEditor = new QtTreePropertyBrowser(dock);
    dock->setWidget(propertyEditor);

加入 Property(属性)

具体的属性 property 由 PropertyManager 创建。property 本身包含了数据模型和 UI 模型,Manager 提供了数据模型,另外需要一个能创建 UI 的类工厂,这样才能在 QtTreePropertyBrowser 中按照设定的操作方式修改属性。下面以 double 类型的属性为例,看看创建过程:

	doubleManager = new QtDoublePropertyManager(this); //创建 Manager
	QtDoubleSpinBoxFactory *doubleSpinBoxFactory = new QtDoubleSpinBoxFactory(this); //创建UI工厂
	propertyEditor->setFactoryForManager(doubleManager, doubleSpinBoxFactory); //关联Manager和UI工厂
	
	QtProperty *property;
    property = doubleManager->addProperty("Position");//用 Manager 创建 property
    propertyEditor->addProperty(property);//加入到 propertyEditor

完整的代码示例

main.cpp

#include <QApplication>
#include "mainwindow.h"

int main(int argc, char **argv)
{
    QApplication app(argc, argv);

    MainWindow mw;
    mw.show();

    return app.exec();
}

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>

class MainWindow : public QMainWindow
{
private:
    class QtDoublePropertyManager *doubleManager;
    class QtColorPropertyManager *colorManager;

    class QtTreePropertyBrowser *propertyEditor;
public:
    MainWindow();
};

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "qtpropertymanager.h"
#include "qteditorfactory.h"
#include "qttreepropertybrowser.h"
#include <QDockWidget>
#include <QGraphicsView>

MainWindow::MainWindow()
{
    QGraphicsView *view = new QGraphicsView(this);
    setCentralWidget(view);

    QDockWidget *dock = new QDockWidget(this);
    addDockWidget(Qt::RightDockWidgetArea, dock);
    propertyEditor = new QtTreePropertyBrowser(dock);
    dock->setWidget(propertyEditor);

    doubleManager   = new QtDoublePropertyManager(this);
    colorManager    = new QtColorPropertyManager(this);

    QtDoubleSpinBoxFactory  *doubleSpinBoxFactory   = new QtDoubleSpinBoxFactory(this);
    QtSpinBoxFactory        *spinBoxFactory         = new QtSpinBoxFactory(this);

    propertyEditor->setFactoryForManager(doubleManager, doubleSpinBoxFactory);
    propertyEditor->setFactoryForManager(colorManager->subIntPropertyManager(), spinBoxFactory);

    QtProperty *property;

    property = doubleManager->addProperty("Position");
    doubleManager->setRange(property, 0, 100);
    doubleManager->setValue(property, 50);
    propertyEditor->addProperty(property);

    property = colorManager->addProperty("Color");
    colorManager->setValue(property, QColor(255, 0,0));
    propertyEditor->addProperty(property);
}

发布了174 篇原创文章 · 获赞 80 · 访问量 35万+

猜你喜欢

转载自blog.csdn.net/quicmous/article/details/104163728
今日推荐