如何在 Qt 中访问其他 class 的对象?

How to access other class's object in Qt?

在程序中,我想点击主window中的一个按钮,触发子window显示图像。但是我无法访问主 window.cpp 中的 ui->graphsView,我该怎么做?在main.cpp。单击按钮功能被假定为做这样的事情。 QGraphicsView 被放置在 ShowPic class.

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QFileSystemModel>
#include "showpic.h"

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    void on_pushButton_clicked();

private:
    Ui::MainWindow *ui;
    QFileSystemModel *model;
    ShowPic *showpic;
    QString filesPath;
};

#endif // MAINWINDOW_H

showpic.h

#ifndef SHOWPIC_H
#define SHOWPIC_H

#include <QWidget>

namespace Ui {
class ShowPic;
}

class ShowPic : public QWidget
{
    Q_OBJECT

public:
    explicit ShowPic(QWidget *parent = 0);
    ~ShowPic();

private:
    Ui::ShowPic *ui;
};

#endif // SHOWPIC_H

main.cpp

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

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

主要window.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<QFileDialog>
#include<QFileSystemModel>
#include<QStringList>
#include <QTreeView>
#include <QGraphicsScene>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{
    showpic = new ShowPic();
    showpic->show();
    QGraphicsScene scene;
    QPixmap pixmap("C:\test\image.jpg");
    scene.addPixmap(pixmap);
    ui->graphicsView->setScene(&scene); ///????
}

showpic.cpp

#include "showpic.h"
#include "ui_showpic.h"

ShowPic::ShowPic(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ShowPic)
{
    ui->setupUi(this);
}

ShowPic::~ShowPic()
{
    delete ui;
}

第一件事是你只需要添加一次QGraphicsScene,一个合适的地方在构造函数中:

ShowPic::ShowPic(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ShowPic)
{
    ui->setupUi(this);
    ui->graphicsView->setScene(new QGraphicsScene);
}

然后我们创建一个接收像素图并将其添加到场景的方法:

showpic.h

[...]
explicit ShowPic(QWidget *parent = 0);
~ShowPic();
void addPixmap(const QPixmap &pixmap);
[...]

showpic.h

[...]
void ShowPic::addPixmap(const QPixmap &pixmap){
    ui->graphicsView->scene()->addPixmap(pixmap);
}
[...]

然后我们在插槽 on_pushButton_clicked:

中使用该方法
void MainWindow::on_pushButton_clicked()
{
    showpic = new ShowPic();
    QPixmap pixmap("C:\test\image.jpg");
    showpic->addPixmap(pixmap);
    showpic->show();
}