在程序中,我想单击主窗口中的一个按钮并触发子窗口以显示图像。但是我无法在主窗口中访问uii> graphSview.cpp,我该怎么做?在main.cpp中。假定点击按钮功能可以执行此类操作。QgraphicsView放置在showpic类中。
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();
}
mainwindow.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);
}
然后,我们创建一种接收PixMap并将其添加到场景的方法:
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();
}