qt之如何自定義一個類,並與mainwindows關聯起來
阿新 • • 發佈:2021-02-20
參考:https://blog.csdn.net/elf001/article/details/8968442
1、自己實現一個類Scene類繼承QGraphicsScene,定義訊號和事件。當滑鼠按下事件發生時,發射訊號message:新增C class檔案
1.1、Scene.h中:
#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.2、Scene.cpp中:
#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) ); }
2、在GUI中mainwindows中
2.1、mainwindow.h中
#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.2、mainwhidow.cpp中
1、例項❀一個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.3、main.cpp中
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}