qt之如何自定義一個類,並與mainwindows關聯起來

參考:https://blog.csdn.net/elf001/article/details/8968442windows

一、本身實現一個類Scene類繼承QGraphicsScene,定義信號和事件。當鼠標按下事件發生時,發射信號message:添加C class文件函數

1.一、Scene.h中:this

#ifndef SCENE_H
#define SCENE_H

class QGraphicsSceneMouseEvent;

#include <QGraphicsScene>

class Scene : public QGraphicsScene
{
  Q_OBJECT
public:
  Scene( );                       // constructor
signals:
  void  message( QString );                                  // 文本消息信號
protected:
  void  mousePressEvent( QGraphicsSceneMouseEvent* );        // 接收鼠標按下事件
};

#endif // SCENE_H

1.二、Scene.cpp中:spa

#include "scene.h"

#include <QGraphicsSceneMouseEvent>

Scene::Scene( ) : QGraphicsScene()
{

}

/********************************** mousePressEvent **********************************/

void  Scene::mousePressEvent( QGraphicsSceneMouseEvent* event )
{
  // 判斷用戶是否按下鼠標左鍵
  if ( event->button() != Qt::LeftButton ) return;

  // 發送信息信號
  qreal  x = event->scenePos().x();
  qreal  y = event->scenePos().y();
  emit message( QString("Clicked at %1,%2").arg(x).arg(y) );
}

二、在GUI中mainwindows中.net

2.一、mainwindow.h中code

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include "scene.h"

class Scene;

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = 0);
    ~MainWindow();
private:
    Scene* m_scene;

public slots:   //添加槽方法的定義
  void showMessage( QString );        // 在狀態欄上顯示消息

};

#endif // MAINWINDOW_H

2.二、mainwhidow.cpp中blog

一、實例❀一個Scene,給mainwindow建立一個場景和視圖:將視圖放入場景,編寫槽函數
#include "mainwindow.h"
#include <QMenuBar>
#include <QStatusBar>
#include <QGraphicsView>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    menuBar()->addMenu( "&File" );
    menuBar()->addMenu( "&Edit" );
    menuBar()->addMenu( "&View" );
    menuBar()->addMenu( "&Simulate" );
    menuBar()->addMenu( "&Help" );

    statusBar()->showMessage("QSimulate has started");

    // 建立場景和顯示場景的中央視圖部件
    m_scene               = new Scene();
    QGraphicsView*   view = new QGraphicsView( m_scene );
    view->setAlignment( Qt::AlignLeft | Qt::AlignTop );
    view->setFrameStyle( 0 );
    setCentralWidget( view );

    //將信號與槽關聯:m_scene發射message信號時,MainWindow接收信號,執行showMessage槽函數
    connect( m_scene, SIGNAL(message(QString)), this, SLOT(showMessage(QString)) );
}

MainWindow::~MainWindow()
{

}

void  MainWindow::showMessage( QString msg )
{
  statusBar()->showMessage( msg );  // 在主窗口狀態欄上顯示消息
}

2.三、main.cpp中繼承

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

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

    return a.exec();
}
相關文章
相關標籤/搜索