【问题标题】:Connection from a Class which inherits from QGraphicsItem to Objects on the ui从继承自 QGraphicsItem 的类到 UI 上的对象的连接
【发布时间】:2015-11-11 21:25:30
【问题描述】:

通常当我想影响 ui 上的对象时,我会在 mainwindow.cpp 中使用它:

ui->nameOfObject.doStuff(); 

但是现在我希望在触发我的类“Ball”的对象的悬停事件时更改 ui 上的对象,但是在文档中挖掘了几个小时后,我还没有找到从 QGraphicsItem 到的接口用户界面。 将数据从我的班级获取到 ui 的最佳方法是什么?

所以我尝试按照答案中的建议进行操作,我的代码现在看起来像这样:

mainwindow.cpp
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    scene = new QGraphicsScene (this);
    scene->setItemIndexMethod(QGraphicsScene::NoIndex);

ui->graphicsView->setScene (scene);
}

void MainWindow::on_createNewBallButton_clicked()
{

    Ball *newBall = new Ball(newBallAngle, newBallRadius, newBallMass, newBallSpeed, newBallxCoordinate, newBallyCoordinate, ui);
    scene->addItem(newBall);
}

球.h

    public:
 Ball(double phi, double r, double m, double v, double x, double y, Ui::MainWindow *uivalue);


Ui::MainWindow *ui;
protected:
void hoverEnterEvent(QGraphicsSceneHoverEvent *event);

球.cpp

Ball::Ball(double phi, double r, double m, double v, double x, double y, Ui::MainWindow *uivalue )
{
    setAngle(phi);
    speed = v;
    mass = m;
    hasCollided = 0;
    radius = r;
    setPos(x, y);
    ui = uivalue;

}

void Ball::hoverEnterEvent(QGraphicsSceneHoverEvent * event)
{
   double outSpeed = this->getV();
   double outAngle = this->getPhi();
   double outMass = this->getM();
   double outRadius = this->getR();
   double outxCoordinate = this->center().x();
   double outyCoordinate = this->center().y();
   ui->radiusOutput.setText(number(outRadius)); //Compiler: invalid use of incomplete type 'class Ui::MainWindow'

}

但是当我尝试构建它时,我会从编译器中收到错误消息。我做错了什么?

【问题讨论】:

    标签: c++ qt interface


    【解决方案1】:

    在大多数情况下,您应该使用信号/槽在 UI 和其他类之间进行通信。但是在这里你处理QGraphicsItem 这不是QObject 子类,所以你不能使用信号/槽。你当然可以使用QGraphicsObject,但它会降低性能。所以解决问题的一种方法是存储指向 UI 对象的指针并使用它进行操作。为这个对象提供 getter/setter。

     void YourItem::hoverEnterEvent(QGraphicsSceneHoverEvent *event)
     {
         if(pointer)
             pointer->setText("Ball!");
     }
    

    【讨论】:

    • 我不太明白,您能否更详细地解释一下如何存储指向 ui 的指针,以便在课堂上调用它?如果该信息具有任何相关性,我想要操作的 ui 对象是 QLineEdit。
    • @Tomathor 非常好!我真的很想为我的答案添加解释,但不幸的是我没有足够的时间早点做。
    • 抱歉,但我仍然无法让它工作,我用我目前正在尝试的代码更新了我的帖子。
    • @Tomathor 你传递了整个 ui 指针,但它非常破坏封装。仅将指针传递给您的 lineEdit。但是如果你还想用ui操作,那么编译器告诉它找不到ui的实现,所以尝试在Ball.cpp中#include "ui_mainwindow.h"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 2013-09-06
    相关资源
    最近更新 更多