【问题标题】:Event handling : Accessing another widget's property事件处理:访问另一个小部件的属性
【发布时间】:2013-08-21 17:21:39
【问题描述】:

好的,这应该很容易。

我尝试将放置事件处理到 QGraphicsView 小部件上。从 QTreeView 小部件拖动的传入数据。为此,我重新实现了这些方法:

void QGraphicsScene::dragEnterEvent(QGraphicsSceneDragDropEvent *event)
{
    event.accept();
}

void QGraphicsScene::dragMoveEvent(QGraphicsSceneDragDropEvent *event)
{
    event.accept();
}

void QGraphicsScene::dropEvent(QGraphicsSceneDragDropEvent *event)
{
    event.accept();
}


void QGraphicsView::dropEvent(QDropEvent *event)
{
    QPixmap pixmap(event->mimedata()->urls()[0].toString().remove(0,8));
    this.scene()->addPixmap(pixmap);
}

这很好用;但是如何在这个小部件的放置事件中更改另一个图形视图场景?那就是:

void QGraphicsView::dropEvent(QDropEvent *event)
{
    QPixmap pixmap(event->mimedata()->urls()[0].toString().remove(0,8));
    // I cannot access ui; and cannot access my widgets...:
    ui->anotherview->scene()->addPixmap(pixmap);
}

【问题讨论】:

    标签: qt drag-and-drop event-handling


    【解决方案1】:

    如何在您的 QGraphicsView 中创建一个自定义信号,例如 void showPixmap(QPixmap p),并将其连接到您的主 gui 类中的一个插槽,您可以在其中访问 ui 元素。然后你可以在 dropEvent 中调用emit showPixamp(pixmap)

    继承 QGraphicsView

    //header file
    class CustomView : public QGraphicsView 
    {
    public:
        CustomView(QGraphicsScene*, QWidget*=NULL);
        ~CustomView();
    
    signals:
        void showPixmap(QPixmap p);
    
    protected:
        virtual void dropEvent(QDropEvent *event);
    };
    
    
    //cpp file
    CustomView::CustomView(QGraphicsScene *scene, QWidget* parent)
        :QGraphicsView(scene, parent) 
    {
        //if you need to initialize variables, etc.
    }
    void CustomView::dropEvent(QDropEvent *event)
    {
        //handle the drop event
        QPixmap mPixmap;
        emit showPixmap(mPixmap);
    }
    

    在主 GUI 类中使用事件过滤器

    void GUI::GUI()
    {     
        ui->mGraphicsView->installEventFilter(this);
    }
    bool GUI::eventFilter(QObject *object, QEvent *event)
    {
        if (object == ui->mGraphicsView && event->type() == QEvent::DropEnter) {
            QDropEvent *dropEvent = static_cast<QDropEvent*>(event);
            //handle the drop event
            return true;
        }
        else
            return false;
    }
    

    【讨论】:

    • 我应该继承图形视图类并从那里创建信号和对象吗?还是应该更改 qgraphicsview 标头?
    • 你说你重新实现了那些方法,怎么样?你不应该改变 QGraphicsView,你应该继承它。
    • 我重写了 QGraphicsScene 和 QGraphicsView 的拖放事件(我实际上得到了“不一致的 dll”警告,但它工作正常)这是错误的做法吗?我应该将我的小部件提升到另一个继承 QGraphicsView 的类中吗?然后在那里放置并重新实现拖动事件?
    • 是的,你应该定义它的子类,然后重新实现你需要使用的方法,或者你可以使用事件过滤器,检查我编辑的答案
    • 哇,我刚刚了解了事件过滤器。它们更容易处理,我真的不需要子类化。谢谢大佬
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多