qqqq

 http://doc.trolltech.com/solutions/qtwinmigrate/winmigrate-walkthrough.html#x8

 

 

Home

MFC to Qt Migration - Walkthrough

Introduction

 

This walkthrough covers the migration of an MFC based program, generated by Microsoft Visual Studio's MFC Application Wizard, to the Qt toolkit using the Windows Migration Framework.

Goals for this Walkthrough

 

The original application, located in the step1 directory, is a trivial SDI program with a main window including a menu bar, a single child view and an about dialog. The walkthrough will demonstrate how easy it is to gradually replace the MFC code in an existing application with multiplatform Qt code, while being able to extend the program with new functionality based on Qt. The final step will be a complete replacement of the Windows-only MFC code with a single source that can be compiled for any platform supported by Qt, including Windows, Mac OS X, Linux/Unix and embedded Linux.

Prerequisites

 

Before we can start using the Windows Migration framework, we must build the framework library, and build and link the MFC project with the Qt toolkit and the Windows Migration framework library.

Building the framework library

 

At the command prompt, run configure to configure the framework. By default MFC is used as a shared library. To use MFC as a static library, run configure -static.

Change into the src directory and run the make tool (nmake for VC++, make for Borland) to build the library. The library qtwinmigrate.lib will be linked into QTDIR/lib.

Getting Started

 

Load the project file qtmfc1.dsp into a Workspace in Visual Studio and make sure that everything is set up correctly by building and running the project.

The MFC application has an interface to use dialogs provided by an external DLL that will be explicitly loaded. The interface is fairly simple: the DLL must export a C function called showDialog that can take a window handle parent. The DLL must show its dialog modally, and when the function returns the DLL is unloaded again.

The code that does this in the MFC application is in the OnAppAbout command handler.

    void WindowsApp::OnAppAbout()
    {
        HMODULE mod = LoadLibrary( "qtdialog.dll" );
        if ( mod ) {
            typedef BOOL(*pShowDialog)(HWND parent);
            pShowDialog showDialog = (pShowDialog)GetProcAddress( mod, "showDialog" );
            if ( showDialog )
                showDialog( theApp.m_pMainWnd->m_hWnd );

            FreeLibrary( mod );
        } else {
            CAboutDlg aboutDlg;
            aboutDlg.DoModal();
        }
    }

If the DLL can be loaded and exports the showDialog symbol the exported function is called, otherwise a default MFC about dialog is displayed.

Plugin extension

 

The project in the qtdll example directory implements the plugin interface using the QMessageBox class. To use this class a QApplication object must exist in the current process, and the Qt events must be processed in addition to the standard event dispatching performed by the running MFC application.

The DLL also has to make sure that it can be loaded together with other Qt based DLLs in the same process (in which case a QApplication object will probably exist already), and that the DLL that creates the QApplication object remains loaded in memory to avoid other DLLs using memory that is no longer available to the process.

All these issues are handled by the QMfcApp::pluginInstance() function. This function creates a QApplication object and installs a message hook that merges the Qt event loop with the existing standard Win32 message pump of MFC. If an instance to the DLL is passed as a parameter the function will also increase the DLL's reference count so that it is not unloaded before the process exits.

This function can be used in an implementation of the DllMain entry point function when the DLL is loaded. A static bool variable is used to remember whether this DLL is responsible for the QApplication object, and when the DLL is unloaded the QApplication object, accessible through the global qApp pointer, can be deleted.

To use the function and the other Qt classes involved we also need to include a few header files.

    #include <qtwinmigrate/qmfcapp.h>
    #include <qtwinmigrate/qwinwidget.h>

    #include <qmessagebox.h>
    #include <windows.h>

    BOOL WINAPI DllMain( HINSTANCE hInstance, DWORD dwReason, LPVOID lpvReserved )
    {
        static bool ownApplication = FALSE;

        if ( dwReason == DLL_PROCESS_ATTACH )
            ownApplication = QMfcApp::pluginInstance( hInstance );
        if ( dwReason == DLL_PROCESS_DETACH && ownApplication )
            delete qApp;

        return TRUE;
    }

The DLL interface is then implemented using an exported C function called showDialog. The QWinWidget class is used to provide the proper placement and stacking of the Qt dialog.

    extern "C" __declspec(dllexport) bool showDialog( HWND parent )
    {
        QWinWidget win( parent );
        win.showCentered();
        QMessageBox::about( &win, "About QtMfc", "QtMfc Version 1.0\nCopyright (C) 2003" );

        return TRUE;
    }

Linking against Qt

 

To use Qt classes directly in the MFC application we must link the application against the Qt library, and add the location of the Qt header files to the compiler's include directories. Open the Project Settings dialog, and switch to the C/C++ page. In the Preprocessor category, add $(QTDIR)/include to the Additional include directories. If Qt is used as a DLL, add QT_DLL as a symbol to the Preprocessor definitions.

Switch to the Link page. In the Input category, add $(QTDIR)/lib to the Additional library paths, and the Qt library, e.g. qt-mt323.lib, as well as qtwinmigrate.lib to the Object/library modules.

Press OK to close the dialog and apply the settings, and make sure that everything is set up correctly by rebuilding the project.

The step2 directory includes a .pro file that generates a proper .dsp file that has all those settings. Run qmake -tp vc in the directory to generate that .dsp file.

Replacing the MFC event loop

 

To be able to use Qt, we need to create a QApplication object. The QApplication class controls the event delivery and display management for all Qt objects and widgets.

In the original MFC project the wizard generated WindowsApp class, a subclass of CWinApp, runs the event loop in the default implementation of Run(). The MFC event loop is a standard Win32 event loop, but uses the CWinApp API PreTranslateMessage() to activate accelerators.

In order to keep MFC accelerators working we must use the QApplication subclass QMfcApp that is provided by the Windows Migration framework and which merges the Qt and the MFC event loops.

The first step of the Qt migration is to reimplement the Run() function in the WindowsApp class. We can either use the wizard to add a reimplementation of Run(), or add the reimplementation ourselves to the class declaration in the qtmfc.h header file:

    class WindowsApp : public CWinApp
    {
    public:
            WindowsApp();

    // Overrides
            // ClassWizard generated virtual function overrides
            //{{AFX_VIRTUAL(WindowsApp)
            public:
            virtual BOOL InitInstance();
            virtual BOOL Run();
            //}}AFX_VIRTUAL

    // Implementation

    public:
            //{{AFX_MSG(WindowsApp)
            afx_msg void OnAppAbout();
            //}}AFX_MSG
            DECLARE_MESSAGE_MAP()
    };

The implementation of this function is in the qtmfc.cpp source file. To use the QMfcApp API we need to #include the qmfcapp.h header file.

    // QtMfc.cpp : Defines the class behaviors for the application.
    //

    #include "stdafx.h"
    #include "qtmfc.h"

    #include "mainframe.h"

    #include <qtwinmigrate/qmfcapp.h>

    BOOL WindowsApp::Run()
    {
        return QMfcApp::run( this );
    }

The implementation uses the static run() function of the QMfcApp class to implicitly instantiate a QApplication object, and run the event loops for both Qt and MFC:

The code in the plugin DLL does not need to be modified: Since we have a QApplication object created in the application itself the pluginInstance() function will do nothing, and the DLL will open the message box in the exported function just like before.

Replacing a Dialog

 

Instead of using the Qt plugin DLL we will now replace the MFC About Dialog directly in the application source code. Using the Visual Studio integration toolbar we can quickly create a new QDialog with Qt Designer from scratch, or convert the dialogs in Microsoft resource files into Qt Designer .ui files, but we can just as well use the QMessageBox::about() function as we did in the plugin code shown earlier.

    // QtMfc.cpp : Defines the class behaviors for the application.
    //

    #include "stdafx.h"
    #include "qtmfc.h"

    #include "mainframe.h"

    #include <qtwinmigrate/qmfcapp.h>
    #include <qtwinmigrate/qwinwidget.h>
    #include <qmessagebox.h>

To use the QMessageBox API we must include the appropriate header. Since we need to create the QMessageBox as a child of the MFC based main window we also need to use the QWinWidget class again and include that header as well.

    // WindowsApp message handlers

    // App command to run the dialog
    void WindowsApp::OnAppAbout()
    {
        QWinWidget win( theApp.m_pMainWnd );
        win.showCentered();
        QMessageBox::about( &win, "About QtMfc", "QtMfc Version 1.0\nCopyright (C) 2003" );
    }

We can remove the class declaration and implementation of the CAboutDlg class from the source file, and use the QWinWidget and QMessageBox API in the implementation of the WindowsApp::OnAppAbout() command handler.

A QWinWidget object is created on the stack, using the MFC application's main window as the parent window. The showCentered() API is used to make sure that the Qt message box, which uses the QWinWidget object as its parent, will open centered over the main window.

New Functionality with Qt

 

We can now add new functionality to the MFC application using Qt. We will add a Qt based user interface to the MFC child view, and add an additional modeless options dialog created with Qt Designer.

Creating Qt widgets

 

To be able to create Qt widgets in the initialization of the MFC application we must first create an instance of QApplication. The current use of the static QMfcApp::run() API creates the QApplication object in the Run() reimplementation of the CWinApp subclass, while the GUI is already being created in the InitInstance reimplementation.

    BOOL WindowsApp::InitInstance()
    {
            // Standard initialization

    #ifdef _AFXDLL
            Enable3dControls();                     // Call this when using MFC in a shared DLL
    #else
            Enable3dControlsStatic();       // Call this when linking to MFC statically
    #endif

            // Change the registry key under which our settings are stored.
            SetRegistryKey(_T("Local AppWizard-Generated Applications"));

            // Qt initialization
            QMfcApp::instance( this );

            MainFrame* pFrame = new MainFrame;
 ... 
            return TRUE;
    }

To create the QApplication object in the InitInstance implementation we must use the static function QMfcApp::instance().

    BOOL WindowsApp::Run()
    {
        int result = QMfcApp::run(this);
        delete qApp;
        return result;
    }

QMfcApp:run() will then use that instance, which must then be deleted explicitly using the global qApp pointer.

MFC's window creation infrastructure is rather complicated, and we must add a message handler for the WM_CREATE and WM_DESTROY messages to be able to add children only when the creation of the MFC window is complete, and to delete the children before the MFC window is destroyed.

    // ChildView window

    class QWinWidget;

    class ChildView : public CWnd
    {
    // Construction
    public:
            ChildView();
 ... 
            // Generated message map functions
    protected:
            //{{AFX_MSG(ChildView)
            afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
            afx_msg void OnDestroy();
            afx_msg void OnPaint();
            //}}AFX_MSG
            DECLARE_MESSAGE_MAP()

    private:
            QWinWidget *widget;
    };

We can again use Visual Studio's wizards, or simply add the code ourselves. We also add a forward declaration of the QWinWidget class, and add a pointer to that class as a member of the ChildView.

    #include "stdafx.h"
    #include "qtmfc.h"
    #include "childview.h"

    #include <qtwinmigrate/qwinwidget.h>
    #include <qlabel.h>
    #include <qlineedit.h>
    #include <qlayout.h>

We include the headers for the Qt widget we want to use, as well as the header for the QWinWidget class.

    ChildView::ChildView()
    : widget( 0 )
    {
    }

We initialize the pointer to the QWinWidget member to zero. We cannot create it yet, since the MFC window has not yet been created. This happens only when the MainWindow::OnCreate() message handler calls the Create function, which then calls our ChildView::OnCreate implementation.

    BEGIN_MESSAGE_MAP(ChildView,CWnd )
            //{{AFX_MSG_MAP(ChildView)
            ON_WM_CREATE()
            ON_WM_DESTROY()
            ON_WM_PAINT()
            //}}AFX_MSG_MAP
    END_MESSAGE_MAP()

The message handlers are added to the message map.

    int ChildView::OnCreate(LPCREATESTRUCT lpCreateStruct)
    {
        if (CWnd::OnCreate( lpCreateStruct ) == -1 )
            return -1;

The implementation of the OnCreate message handler calls and verifies the parent class function and returns an error code if an error occurred.

        widget = new QWinWidget( this );
        QHBoxLayout *hbox = new QHBoxLayout( widget );

        QLabel *label = new QLabel( "Enter text:", widget );
        QLineEdit *edit = new QLineEdit( widget );
        hbox->addWidget( label );
        hbox->addWidget( edit );

        widget->move( 0, 0 );
        widget->show();

        return 0;
    }

Now we can create the QWinWidget instance with this CWnd instance as a parent window, and use that instance as a parent to the QWidgets we want to use to create the user interface. Since QWinWidget is a proper QWidget it can be laid out, and we move the Qt GUI to the upper left corner of the MFC child and show() the user interface immediately.

    BOOL ChildView::PreCreateWindow(CREATESTRUCT& cs)
    {
            if (!CWnd::PreCreateWindow(cs))
                    return FALSE;

            cs.dwExStyle |= WS_EX_CLIENTEDGE;
            cs.style &= ~WS_BORDER;
            cs.style |= WS_CLIPCHILDREN;
            cs.lpszClass = AfxRegisterWndClass(CS_HREDRAW|CS_VREDRAW|CS_DBLCLKS,
                    ::LoadCursor(NULL, IDC_ARROW), HBRUSH(COLOR_WINDOW+1), NULL);

            return TRUE;
    }

Since the ChildView class of MFC was not supposed to be a container for other windows we now see some bad flickering whenever we resize the main window. The QLabel widget is obviously painted over by the ChildView window on every resize before it has a chance to fill its own background. To prevent this we must change the style of the window to include the CS_CLIPCHILDREN flag.

    void ChildView::OnDestroy()
    {
        delete widget;
        widget = 0;

        CWnd::OnDestroy();
    }

In the OnDestroy message handler we delete the QWinWidget instance, which deletes all other QWidgets we have created as children.

A new Qt Dialog

 

To add a new dialog we use the Visual Studio integration toolbar's "New Qt Dialog" button. We add a Qt Designer .ui file "optionsdialog.ui" to the current project, and add the required build steps to generate a C++ class from that file. (1) MFC projects have the precompiled header option turned on by default, and since Qt or Qt Designer cannot rely on the compiler used supporting precompiled headers the respective preprocessor directives are missing from the generated .cpp files. We must turn the precompiled headers option off for those files, but we can just as well turn them off for the complete project.

To be able to invoke the dialog we add a new entry to the MFC menu using the Visual Studio resource editor. The menu entry is called "Options", and has the ID ID_EDIT_OPTIONS.

    class WindowsApp : public CWinApp
    {
    public:
 ... 
    // Implementation

    public:
            //{{AFX_MSG(WindowsApp)
            afx_msg void OnAppAbout();
            afx_msg void OnAppOptions();
            //}}AFX_MSG
            DECLARE_MESSAGE_MAP()
    };

We add a command handler for that option to the WindowsApp class and add the mapping to the message map. We also include the generated header file.

    #include <qtwinmigrate/qmfcapp.h>
    #include <qtwinmigrate/qwinwidget.h>
    #include <qmessagebox.h>
    #include "optionsdialog.h"
    BEGIN_MESSAGE_MAP(WindowsApp, CWinApp)
            //{{AFX_MSG_MAP(WindowsApp)
            ON_COMMAND(ID_APP_ABOUT, OnAppAbout)
            ON_COMMAND(ID_EDIT_OPTIONS, OnAppOptions)
            //}}AFX_MSG_MAP
    END_MESSAGE_MAP()

The implementation of the command handler once again uses the QWinWidget class to make sure that the dialog is properly positioned and stacked. Since we want the dialog to be modeless we cannot create the QWinWidget on the stack, since it would be deleted when it leaves the scope, and all its children, including the dialog, would be deleted as well.

    void WindowsApp::OnAppOptions()
    {
        QWinWidget *win = new QWinWidget( theApp.m_pMainWnd );
        win->showCentered();

        OptionsDialog *dialog = new OptionsDialog( win, 0, FALSE, Qt::WDestructiveClose );
        dialog->show();
    }

Instead we create QWinWidget on the heap, using operator new, and use the WDestructiveClose widget flag when creating the dialog as a child, also with operator new.

Both the QWinWidget object and the modeless dialog will be destroyed when the dialog is closed, e.g. when clicking the OK button.

Removing MFC

 

We will now turn the complete MFC/Qt hybrid application into a genuine, multiplatform Qt application. To make our application compilable with different compilers for different platforms we need to remove the dependency on Visual C++ and Visual Studio, and replace the Visual Studio project file with a qmake project.

Using the Qt build system

 

The project file lists all the sources involved.

    TEMPLATE = app

    SOURCES += childview.cpp mainframe.cpp qtmfc.cpp
    HEADERS += childview.h   mainframe.h
    FORMS   += optionsdialog.ui
    RC_FILE = qtmfc.rc

    DEFINES -= UNICODE
    DEFINES += _AFXDLL
    QMAKE_LIBS_QT_ENTRY =
    LIBS    += -lqtwinmigrate

Until we have completed the transition we must still link against the Windows Migration Framework, compile the Visual C++ resources, set the preprocessor define to pull in the MFC DLL, and turn off UNICODE to avoid library conflicts with the non-UNICODE MFC version. We must also remove the qtmain library which implements the WinMain entry point function to call the multiplatform main entry point.

Running qmake -tp vc on the .pro file will generate a new .dsp file that we can use in Visual Studio to compile and link the application.

Replacing the ChildView

 

The first MFC class we will move over to Qt is the ChildView class. We replace the old class declaration with the declaration of a QWidget subclass.

    #ifndef CHILDVIEW_H
    #define CHILDVIEW_H

    #include <qwidget.h>

    class ChildView : public QWidget
    {
    public:
        ChildView( QWidget *parent = 0, const char *name = 0 );

    protected:
        void paintEvent( QPaintEvent * );
    };

    #endif

We don't need any creation and destruction message handlers anymore, and the QWinWidget member is obsolete as well. However, we will keep an event handler for paint events as in the original class.

    ChildView::ChildView( QWidget *parent, const char *name )
    : QWidget( parent, name )
    {
        QHBox *hbox = new QHBox( this );

        QLabel *label = new QLabel( "Enter text:", hbox );
        QLineEdit *edit = new QLineEdit( hbox );

        hbox->move( 0, 0 );
        setEraseColor( white );
    }

    void ChildView::paintEvent( QPaintEvent *e )
    {
        QPainter painter( this );
    }

The implementation of the class creates the user interface elements directly in the constructor and sets the erase color property to white. The paintEvent does nothing, at least for now.

Replacing the MainFrame

 

The next MFC class we will move over to Qt is the MainFrame class. We could use Qt Designer to generate a main window in a visual environment, but it's just as easy to add the few elements manually.

    #ifndef MAINFRAME_H
    #define MAINFRAME_H

    #include <qmainwindow.h>

    class ChildView;

    class MainFrame : public QMainWindow
    {
        Q_OBJECT
    public:
        MainFrame( QWidget *parent = 0, const char *name = 0 );

    protected slots:
        void editOptions();
        void helpAbout();

    private:
        ChildView *view;
    };

    #endif

The class implements the constructor, and keeps a reference to the ChildView object. The Q_OBJECT macro is used to allow this class to declare signals and slots. We add two slots, editOptions and helpAbout.

    MainFrame::MainFrame( QWidget *parent, const char *name )
    : QMainWindow( parent, name )
    {
        QPopupMenu *filePopup = new QPopupMenu( this );
        QAction *action = new QAction( "Exit", "E&xit", 0, this );
        action->addTo( filePopup );
        connect( action, SIGNAL(activated()), this, SLOT(close()) );

        QPopupMenu *editPopup = new QPopupMenu( this );
        action = new QAction( "Undo", "&Undo", CTRL+Key_Z, this );
        action->addTo( editPopup );
        editPopup->insertSeparator();
        action = new QAction( "Cut", "Cu&t", CTRL+Key_X, this );
        action->addTo( editPopup );
        action = new QAction( "Copy", "&Copy", CTRL+Key_C, this );
        action->addTo( editPopup );
        action = new QAction( "Paste", "&Paste", CTRL+Key_V, this );
        action->addTo( editPopup );
        editPopup->insertSeparator();
        action = new QAction( "Options", "&Options...", 0, this );
        action->addTo( editPopup );
        connect( action, SIGNAL(activated()), this, SLOT(editOptions()) );

        QPopupMenu *helpPopup = new QPopupMenu( this );
        action = new QAction( "About", "&About QtMfc...", CTRL+Key_F1, this );
        action->addTo( helpPopup );
        connect( action, SIGNAL(activated()), this, SLOT(helpAbout()) );

        menuBar()->insertItem( "&File", filePopup );
        menuBar()->insertItem( "&Edit", editPopup );
        menuBar()->insertItem( "&Help", helpPopup );

        view = new ChildView( this );
        setCentralWidget( view );

        statusBar();
    }

The implementation of the class creates the menu, instantiates the ChildView as the central widget, and adds a status bar.

    void MainFrame::editOptions()
    {
        OptionsDialog *dialog = new OptionsDialog( this, 0, FALSE, Qt::WDestructiveClose );
        dialog->show();
    }

    void MainFrame::helpAbout()
    {
        QMessageBox::about( this, "About QtMfc", "QtMfc Version 1.0\nCopyright (C) 2003" );
    }

The slot implementations are identical to the application command handlers in the Qt/MFC hybrid, but of course don't need to use the QWinWidget class anymore.

Replacing the MFC application

 

The final step is to remove the WindowsApp class completely, and handle the application startup and initialization in a multiplatform main entry point function.

    TEMPLATE = app

    SOURCES += childview.cpp mainframe.cpp qtmfc.cpp
    HEADERS += childview.h   mainframe.h
    FORMS   += optionsdialog.ui
    RC_FILE = qtmfc.rc

We can delete the qtmfc.h header file and remove it from the HEADERS section in the qmake .pro file. We can also remove the linking against the Migration Framework library, and the modifications of the preprocessor symbols.

Then we rerun qmake to regenerate the .dsp file. Since we added the Q_OBJECT macro to the MainFrame class declaration we have to make sure that the meta object compiler, moc, is added to the build step for the MainFrame class, and this is also done when running qmake.

The qtmfc.cpp file is completely replaced.

    #include <qapplication.h>
    #include "mainframe.h"

    int main( int argc, char **argv )
    {
        QApplication app( argc, argv );

        MainFrame frame;
        frame.show();

        app.setMainWidget( &frame );
        return app.exec();
    }

All it does now is to include the required headers, and to implement a standard main entry point function.

Cleaning up

 

Finally we edit the res

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值