MFC program using visual c++ - visual-c++

I am getting the following warning after I debug the MFC based windows application(visual C++). The problem is that it does not display the window. Why is it so?
Warning: m_pMainWnd is NULL in CWinApp::Run - quitting application.
The program '[2616] new.exe: Native' has exited with code 0 (0x0).
The code is:
#include <afxwin.h>
#include "stdafx.h"
class myframe:public CFrameWnd
{
public:
myframe()
{
Create(0,TEXT("On single Left Mouse Button Click"));
}
void OnLButtonDown(UINT flag,CPoint pt)
{
CClientDC d(this);
d.SetTextColor(RGB(0,0,255));
d.TextOutW(pt.x,pt.y,TEXT("Hello"),5);
}
DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(myframe,CFrameWnd)
ON_WM_LBUTTONDOWN()
END_MESSAGE_MAP()
class myapp:public CWinApp
{
public:
int InitInsatnce()
{
myframe *p;
p=new myframe;
p->ShowWindow(3);
m_pMainWnd=p;
return 1;
}
};
myapp a;

Fix the typo: InitInsatnce should be InitInstance then your window will be initialised and displayed.

Related

Problem in restoring floating toolbar for QMainWindow

I am seeing a problem while restoring QMainWindow state having QCombobox in floating toolbar. After restoring floating toolbar, my QCombobox is not able to get focus until i click on toolbar handle and move it.
Following is gif showing problem, Using QT 5.13.
File floating_toolbar.pro
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = floating_toolbar
TEMPLATE = app
DEFINES += QT_DEPRECATED_WARNINGS
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
CONFIG += c++11
SOURCES += \
main.cpp \
mainwindow.cpp
HEADERS += \
mainwindow.h
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
File : main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
File : mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = 0);
void closeEvent(QCloseEvent *event);
void readSettings();
bool eventFilter(QObject* xObj, QEvent* xEvent);
~MainWindow();
public slots:
void mCheck();
};
#endif // MAINWINDOW_H
File : mainwindow.cpp
#include "mainwindow.h"
#include <QToolBar>
#include <QComboBox>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLayout>
#include <QSettings>
#include <QEvent>
#include <QDebug>
#include <QMouseEvent>
#include <QApplication>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
QToolBar* lToolbar = new QToolBar(this);
QComboBox* lComobox = new QComboBox(this);
lComobox->setEditable(true);
lToolbar->setWindowTitle("MyToolBar");
lToolbar->setObjectName("NiceBaby");
lToolbar->addWidget(lComobox);
//lToolbar->addAction("check", lComobox, SLOT(clearEditText()));
addToolBar(lToolbar);
lToolbar->installEventFilter(this);
readSettings();
}
void MainWindow::mCheck()
{
}
void MainWindow::closeEvent(QCloseEvent *event)
{
QSettings settings("MyCompany", "MyApp");
settings.setValue("windowState", saveState());
QMainWindow::closeEvent(event);
}
void MainWindow::readSettings()
{
QSettings settings("MyCompany", "MyApp");
restoreState(settings.value("windowState").toByteArray());
}
MainWindow::~MainWindow()
{
}
bool MainWindow::eventFilter(QObject* xObj, QEvent* xEvent)
{
//qDebug()<<xEvent->type();
return QMainWindow::eventFilter(xObj, xEvent);
}
OK, a workaround is to reset the window flags on the toolbar when it is first shown and is floating. I tracked this down by seeing what happens once a toolbar is dropped after being dragged (but not plugged into main window). (It calls setWindowState() and all that does in this situation is hide the toolbar, call updateWindowFlags(), and show it again).
This could be handled from the QMainWindow::showEvent() or from the eventFilter installed onto the QToolBar. I think it's simpler from the former.
UPDATE: This problem actually happens whenever the toolbar is first shown even if not at app startup, e.g. from the toggle view menu by the user once app starts. I updated the code below to fix that issue as well. And see notes below about another issue with minimizing the main window.
I added this to the MainWindow class from the MCVE:
protected:
void showEvent(QShowEvent *e) override {
QMainWindow::showEvent(e);
#ifdef Q_OS_LINUX
if (lToolbar->isFloating()
// remove the next condition and the toolsbar will get hidden the 2nd time main window is minimized.
&& lToolbar->windowFlags().testFlag(Qt::X11BypassWindowManagerHint)
) {
const bool vis = !lToolbar->isHidden();
qDebug() << lToolbar->isFloating() << vis << lToolbar->windowFlags();
lToolbar->hide();
lToolbar->setWindowFlag(Qt::X11BypassWindowManagerHint, false);
if (vis)
lToolbar->show();
#endif
}
QToolBar* lToolbar; // Use this in MainWindow constructor to save the instance pointer.
I also noticed another issue with the initially-floating toolbar. When the main window is minimized, the toolbar doesn't get hidden but stays where it was on the screen. Regardless of what is in the toolbar (eg. no combo box, just QActions). This workaround could also sort-of address that issue (see code comment), but only the 2nd time the window is minimized. Needs a better workaround for the first minimize.
Can others confirm this? Potentially a larger issue than the editable combo and I'd be surprised if no one noticed before.
I guess this should be filed as a Qt bug either way.
UPDATE2: This version also fixes the minimize issue. I guess something happens after the QMainWindow::showEvent() that changes how the toolbar behaves. Which explains why the above workaround works only after the 1st minimize. So scheduling the toolbar "fix" for later works around that also.
class MainWindow : public QMainWindow
{
...
#ifdef Q_OS_LINUX
protected:
void showEvent(QShowEvent *e) override
{
QMainWindow::showEvent(e);
if (lToolbar->isFloating() && lToolbar->windowFlags().testFlag(Qt::X11BypassWindowManagerHint) ) {
// QMainWindow::show() after QMainWindow::restoreState() will break the minimizing again so we should delay calling adjustToolbar().
QMetaObject::invokeMethod(this, "adjustToolbar", Qt::QueuedConnection);
// If we're sure restoreState() is only called after show() then adjustToolbar() could be called here directly instead.
//adjustToolbar();
}
}
private slots:
void adjustToolbar() const
{
const bool vis = !lToolbar->isHidden();
qDebug() << lToolbar->isFloating() << vis << lToolbar->windowFlags();
lToolbar->hide();
lToolbar->setWindowFlag(Qt::X11BypassWindowManagerHint, false);
if (vis)
lToolbar->show();
}
#endif
private:
QToolBar* lToolbar;
};
ADDED: A QToolBar subclass which applies the workaround on its own, nothing special needed in the QMainWindow. The minimize fix still only works when the adjustToolbar() function is queued or if restoreState() is only called after show() (see code comments).
class ToolBar : public QToolBar
{
Q_OBJECT
public:
using QToolBar::QToolBar;
#ifdef Q_OS_LINUX
protected:
void showEvent(QShowEvent *e) override
{
QToolBar::showEvent(e);
if (isFloating() && windowFlags().testFlag(Qt::X11BypassWindowManagerHint) ) {
// QMainWindow::show() after QMainWindow::restoreState() will break the minimizing again so we should delay calling adjustToolbar().
QMetaObject::invokeMethod(this, "adjustToolbar", Qt::QueuedConnection);
// If we're sure restoreState() is only called after show() then adjustToolbar() could be called here directly instead.
//adjustToolbar();
}
}
private slots:
void adjustToolbar()
{
const bool vis = !isHidden();
hide();
setWindowFlag(Qt::X11BypassWindowManagerHint, false);
if (vis)
show();
}
#endif
};
UPDATE3: The minimizing issue also exists with floating QDockWidget if the QMainWindow state is restored before it is shown. In fact with "older" Qt versions the floating widget doesn't show up at all (doesn't with <= 5.9.5 but does with >= 5.12.4, don't have anything in between to try ATM). So the proper approach is to show() the main window first and then restoreState(). Unfortunately this doesn't seem to work for QToolBar.
UPDATE4: Filed as QTBUG-78293
It seems to work normally on macOS:

Unhandled exception at 0x77f8f397 in test.exe: 0xC0000005: Access violation writing location 0x00030ff0 &&& CXX0013: Error: missing operator

I wrote a program in visual C++ to display position and velocity. It worked fine. When I extended the code to display error. Eventhough I just added from visual studio. I get the access violation error, The error in code occurs first at "CEdit" from testDLg.h. Class CEdit is produced by default in axfwin.h by visual studio in windows.
// testDlg.cpp : implementation file
//
#include "stdafx.h"
#include "test.h"
#include "testDlg.h"
//#include <timer.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
#pragma comment(lib,"Mx4nt.lib")
extern "C"
{
#include "mx4nt.h"
#include "mx4dll.h"
int pstn = 0;
// The following function is not included in the DLL's header file, but
// it is included in the DLL.
NOMANGLE BYTE _stdcall r_1byte( int offset );
NOMANGLE BYTE _stdcall w_1byte( int offset, unsigned char data );
}
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()
// CtestDlg dialog
CtestDlg::CtestDlg(CWnd* pParent /*=NULL*/)
: CDialog(CtestDlg::IDD, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CtestDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_EDIT10, tab1);
DDX_Control(pDX, IDC_EDIT11, tab2);
DDX_Control(pDX, IDC_EDIT12, tab3);
DDX_Control(pDX, IDC_EDIT13, tab4);
DDX_Control(pDX, IDC_EDIT14, tab5);
DDX_Control(pDX, IDC_EDIT15, tab6);
DDX_Control(pDX, IDC_EDIT16, tab7);
DDX_Control(pDX, IDC_EDIT1, pos1);
DDX_Control(pDX, IDC_EDIT3, pos2);
DDX_Control(pDX, IDC_EDIT5, pos3);
DDX_Control(pDX, IDC_EDIT7, pos4);
DDX_Control(pDX, IDC_EDIT2, vel1);
DDX_Control(pDX, IDC_EDIT4, vel2);
DDX_Control(pDX, IDC_EDIT6, vel3);
DDX_Control(pDX, IDC_EDIT8, vel4);
DDX_Control(pDX, IDC_EDIT9, ferr1);
DDX_Control(pDX, IDC_EDIT17, ferr2);
DDX_Control(pDX, IDC_EDIT18, ferr3);
DDX_Control(pDX, IDC_EDIT19, ferr4);
}
BEGIN_MESSAGE_MAP(CtestDlg, CDialog)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
//}}AFX_MSG_MAP
ON_WM_TIMER()
END_MESSAGE_MAP()
// CtestDlg message handlers
BOOL CtestDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
clear_dspl();
reset_MX4();
SetTimer(1,50,NULL);
// TODO: Add extra initialization here
GetDlgItem(IDC_EDIT10)->SetWindowText("axis1");
GetDlgItem(IDC_EDIT11)->SetWindowText("axis2");
GetDlgItem(IDC_EDIT12)->SetWindowText("axis3");
GetDlgItem(IDC_EDIT13)->SetWindowText("axis4");
GetDlgItem(IDC_EDIT14)->SetWindowText("position");
GetDlgItem(IDC_EDIT15)->SetWindowText("velocity");
GetDlgItem(IDC_EDIT16)->SetWindowText("error");
GetDlgItem(IDC_EDIT1)->SetWindowText("");
GetDlgItem(IDC_EDIT2)->SetWindowText("");
GetDlgItem(IDC_EDIT3)->SetWindowText("");
GetDlgItem(IDC_EDIT4)->SetWindowText("");
GetDlgItem(IDC_EDIT5)->SetWindowText("");
GetDlgItem(IDC_EDIT6)->SetWindowText("");
GetDlgItem(IDC_EDIT7)->SetWindowText("");
GetDlgItem(IDC_EDIT8)->SetWindowText("");
GetDlgItem(IDC_EDIT9)->SetWindowText("");
GetDlgItem(IDC_EDIT17)->SetWindowText("");
GetDlgItem(IDC_EDIT18)->SetWindowText("");
GetDlgItem(IDC_EDIT19)->SetWindowText("");
pos_preset(1, pstn);
return TRUE; // return TRUE unless you set the focus to a control
}
void CtestDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CtestDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
/*
CString str[8];
str[0].Format("%f",pos(1));
str[1].Format("%f",pos(2));
str[2].Format("%f",pos(3));
str[3].Format("%f",pos(4));
str[4].Format("%f",vel(1));
str[5].Format("%f",vel(2));
str[6].Format("%f",vel(3));
str[7].Format("%f",vel(4));
GetDlgItem(IDC_EDIT1)->SetWindowText(str[0]);
GetDlgItem(IDC_EDIT3)->SetWindowText(str[1]);
GetDlgItem(IDC_EDIT5)->SetWindowText(str[2]);
GetDlgItem(IDC_EDIT7)->SetWindowText(str[3]);
GetDlgItem(IDC_EDIT2)->SetWindowText(str[4]);
GetDlgItem(IDC_EDIT4)->SetWindowText(str[5]);
GetDlgItem(IDC_EDIT6)->SetWindowText(str[6]);
GetDlgItem(IDC_EDIT8)->SetWindowText(str[7]);
*/
}
// The system calls this function to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CtestDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void CtestDlg::OnTimer(UINT nIDEvent)
{
// TODO: Add your message handler code here and/or call default
//pstn += 100;
//pos_preset(1, pstn);
maxacc(1, 1.0);
velmode(1, 1.0);
CString str[8];
str[0].Format("%f",pos(1));
str[1].Format("%f",pos(2));
str[2].Format("%f",pos(3));
str[3].Format("%f",pos(4));
str[4].Format("%f",vel(1));
str[5].Format("%f",vel(2));
str[6].Format("%f",vel(3));
str[7].Format("%f",vel(4));
str[8].Format("%f",ferr(1));
str[9].Format("%f",ferr(2));
str[10].Format("%f",ferr(3));
str[11].Format("%f",ferr(4));
GetDlgItem(IDC_EDIT1)->SetWindowText(str[0]);
GetDlgItem(IDC_EDIT3)->SetWindowText(str[1]);
GetDlgItem(IDC_EDIT5)->SetWindowText(str[2]);
GetDlgItem(IDC_EDIT7)->SetWindowText(str[3]);
GetDlgItem(IDC_EDIT2)->SetWindowText(str[4]);
GetDlgItem(IDC_EDIT4)->SetWindowText(str[5]);
GetDlgItem(IDC_EDIT6)->SetWindowText(str[6]);
GetDlgItem(IDC_EDIT8)->SetWindowText(str[7]);
GetDlgItem(IDC_EDIT9)->SetWindowText(str[8]);
GetDlgItem(IDC_EDIT17)->SetWindowText(str[9]);
GetDlgItem(IDC_EDIT18)->SetWindowText(str[10]);
GetDlgItem(IDC_EDIT19)->SetWindowText(str[11]);
//KillTimer(1);
//i = i+100;
//Invalidate();
CDialog::OnTimer(nIDEvent);
}
--
- Nandhini
www.linkedin.com/in/nandhinisudarsanan
// testDlg.h : header file
//
#pragma once
#include "afxwin.h"
// CtestDlg dialog
class CtestDlg : public CDialog
{
// Construction
public:
CtestDlg(CWnd* pParent = NULL); // standard constructor
// Dialog Data
enum { IDD = IDD_TEST_DIALOG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
HICON m_hIcon;
// Generated message map functions
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
DECLARE_MESSAGE_MAP()
public:
CEdit tab1;
CEdit tab2;
CEdit tab3;
CEdit tab4;
CEdit tab5;
CEdit tab6;
CEdit tab7;
CEdit pos1;
CEdit pos2;
CEdit pos3;
CEdit pos4;
CEdit vel1;
CEdit vel2;
CEdit vel3;
CEdit vel4;
CEdit ferr1;
CEdit ferr2;
CEdit ferr3;
CEdit ferr4;
afx_msg void OnTimer(UINT nIDEvent);
};
The result I got from debugging.
NTDLL.DLL!77f8f397()
NTDLL.DLL!77fa0346()
mfc70d.dll!AfxWinMain(HINSTANCE__ * hInstance=, HINSTANCE__ * hPrevInstance=, char * lpCmdLine=, int nCmdShow=) Line 23 C++
hInstance CXX0017: Error: symbol "" not found HINSTANCE__ *
unused CXX0030: Error: expression cannot be evaluated int
hPrevInstance CXX0030: Error: expression cannot be evaluated HINSTANCE__ *
unused CXX0030: Error: expression cannot be evaluated int
lpCmdLine CXX0030: Error: expression cannot be evaluated char *
CXX0030: Error: expression cannot be evaluated char
nCmdShow CXX0030: Error: expression cannot be evaluated int
HINSTANCE__* should equal some value where as nothing has been found there. I am receiving
77F8F397 CXX0013: Error: missing operator
Need help unpacking this Thanks.
Update :
I removed unnecessary CEdits. It doesn't produce any errors. The value for velocity and error is constantly zero, eventhough I know it should not display a zero.
Use debugger!
Run your application under debugger (F5 by default in Visual Studio).
When exception will be thrown, press "Break". Application execution will be halted (debug breakpoint), and source code location of error will be shown.
If error location is out of your code (probably somewhere in library code), look at "Call Stack" window and pick topmost function that you recognize. You will jump to location in your code that caused further problems.
Look at "Autos" and "Locals" windows. Inspect values of variables, compare with values you expect. You will be able to find mistake quickly.
Happy debugging!

How to use signals & slots in Qt for inter-threading communication

I want to make an application where the user will hit a QPushButton and this will trigger a secondary thread which will add some text to a QListWidget in the main window. But for a reason that I cannot figure out ,although the signal from the thread to the main window is emitted it never reaches the destination. Probably because the connection fails. But why this happens here is my code(my application is compiled using Visual Studio 2010):
mythread.h
#ifndef MY_THREAD_H
#define MY_THREAD_H
#include <QThread>
#include <QString>
class mythread:public QThread
{
Q_OBJECT
public:
void setName(QString& name);
signals:
void sendMsg(QString& msg);
protected:
void run();
private:
QString m_name;
QString msg;
};
#endif
mythread.cpp
#include "mythread.h"
void mythread::setName(QString& name)
{
m_name=name;
}
void mythread::run()
{
msg="Hello "+m_name;
emit sendMsg(msg);
}
mydialog.h:
#ifndef MY_DIALOG_H
#define MY_DIALOG_H
#include <QtGui>
#include "mythread.h"
class mydialog:public QDialog
{
Q_OBJECT
public:
mydialog();
public slots:
void receiveMsg(QString& msg);
void fillList();
private:
QListWidget list1;
QPushButton btn1;
QGridLayout layout;
mythread thread;
};
#endif
mydialog.cpp:
#include "mydialog.h"
mydialog::mydialog()
{
layout.addWidget(&list1,0,0);
btn1.setText("Find");
layout.addWidget(&btn1,0,1);
setLayout(&layout);
QString myname="leonardo";
thread.setName(myname);
connect(&btn1,SIGNAL(clicked()),this,SLOT(fillList()));
connect(&thread,SIGNAL(sendMsg(QString&)),this,SLOT(receiveMsg(Qstring&)));
}
void mydialog::fillList()
{
thread.start();
}
void mydialog::receiveMsg(QString& msg)
{
list1.addItem(msg);
}
find.cpp:
#include <QApplication>
#include "mydialog.h"
int main(int argc,char* argv[])
{
QApplication app(argc,argv);
mydialog window;
window.setWindowTitle("Find");
window.show();
return app.exec();
}
find.pro:
TEMPLATE = app
TARGET =
DEPENDPATH += .
INCLUDEPATH += .
# Input
HEADERS += mydialog.h mythread.h
SOURCES += find.cpp mydialog.cpp mythread.cpp
Two things:
In your second connect call, Qstring must be changed to QString
Qt cannot deliver QString& accross threads by default. There's two ways to fix this:
Change your Signals and Slots and the connect to use QString rather than QString&
Use qRegisterMetaType in order to make QString& usable.
I still recommend reading
https://www.qt.io/blog/2010/06/17/youre-doing-it-wrong
and Kari's comment
https://www.qt.io/blog/2010/06/17/youre-doing-it-wrong#commento-comment-name-a6fad43dec11ebe375cde77a9ee3c4331eb0c5f0bcac478ecbe032673e8ebc82
when working with threads, though.
First of all use const qualifier for arguments if you're not planning to modify it. After fixing typo in connection SLOT(receiveMsg(Qstring&)) and changing signals and slots signature to const references everything works fine

VC++ does not show output

I am new to VC++ and its been a few times now, and this is the third program that does not give output even after it is build succesfully.
#include <AFXWIN.H>
#include <math.h>
#define PI 3.1415926
#define SEGMENTS 500
class CMyApp : public CWinApp {
public:
virtual BOOL InitInstance();
};
class CMainWindow : public CFrameWnd
{
public:
CMainWindow();
protected:
afx_msg void OnPaint();
afx_msg void OnLButtonDown(UINT, CPoint);
DECLARE_MESSAGE_MAP();
};
CMyApp myAPP;
BOOL CMyApp::InitInstance() {
m_pMainWnd = new CMainWindow;
m_pMainWnd->ShowWindow(SW_MAXIMIZE);
m_pMainWnd->UpdateWindow();
return TRUE;
}
BEGIN_MESSAGE_MAP (CMainWindow, CFrameWnd)
ON_WM_PAINT ()
END_MESSAGE_MAP ()
CMainWindow::CMainWindow() {
Create(NULL,"The Hello Application",WS_OVERLAPPEDWINDOW);
}
void CMainWindow::OnPaint() {
CRect rect;
int nWidth = rect.Width();
int nHeight = rect.Height();
CPaintDC dc (this);
CPoint aPoint[SEGMENTS];
for (int i =0; i < SEGMENTS; i++){
aPoint[i].x = ((i*nWidth)/SEGMENTS );
aPoint[i].y= (int)((nHeight/2)* (1-(sin((2*PI*i)/SEGMENTS))));
}
dc.Polyline(aPoint, SEGMENTS);
UpdateData(false);
}
The above program should give Sine curve as the output, except that I get a blank window. And I don't know why does it happen. If it helps, I am using VC++ 6.0
The problem is probably that the rectangle you use to get the width and height is not initialized. You have to get the rectangle from somewhere, see e.g. CWnd::GetClientRect.

QGraphicsTextItem mouseDoubleClickEvent

I am a new guy for QT. Now a question confuses me.
Code in the MainWindow as follows:
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
QGraphicsView *view = new QGraphicsView;
QGraphicsScene *scene =new QGraphicsScene;
GraphicsTextItem *item = (GraphicsTextItem*)scene->addText(QString("hello world"));
item->setPos(100,100);
scene->addItem(item);
QGraphicsItem *i = scene->itemAt(120,110);
view->setScene(scene);
view->show();
}
class GraphicsTextItem inherits QGraphicsTextItem and protected method mousePressDown is reimplemented as follows:
void GraphicsTextItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
{
qDebug()<<"mouseDoubleClickEvent happens";
QGraphicsTextItem::mouseDoubleClickEvent(event);
}
The application can works normally, but when I give the GraphicsTextItem object double click, nothing happens to the mouseDoubleClickEvent in class GraphicsTextItem.
Be expecting your response!
I searched my code and I developed an example, because I was left with the question but here it is:
#include <QGraphicsTextItem>
class GraphicsTextItem : public QGraphicsTextItem
{
Q_OBJECT
public:
GraphicsTextItem(QGraphicsItem * parent = 0);
protected:
void mouseDoubleClickEvent ( QGraphicsSceneMouseEvent * event );
};
implementation:
#include "graphicstextitem.h"
#include <QDebug>
#include <QGraphicsSceneMouseEvent>
GraphicsTextItem::GraphicsTextItem(QGraphicsItem * parent)
:QGraphicsTextItem(parent)
{
setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
}
void GraphicsTextItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
{
if (textInteractionFlags() == Qt::NoTextInteraction)
setTextInteractionFlags(Qt::TextEditorInteraction);
QGraphicsItem::mouseDoubleClickEvent(event);
}
the view
#include "mainwindow.h"
#include <QtGui>
#include <QtCore>
#include "graphicstextitem.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent)
{
QGraphicsScene * scene = new QGraphicsScene();
QGraphicsView * view = new QGraphicsView();
view->setScene(scene);
GraphicsTextItem * text = new GraphicsTextItem();
text->setPlainText("Hello world");
scene->addItem(text);
text->setPos(100,100);
text->setFlag(QGraphicsItem::ItemIsMovable);
setCentralWidget(view);
}
in this example you can interact with and change the text QGraphicsTextItem by doubleclick. I hope you will be helpful.

Resources