Set focus on a modeless dialogs hosted in an MFC view - c++

I have an MFC view, and I have another project which implements and MFC dialog.
I want to host the dialog in my view.
My view is of class CFormView.
I did it that way in my view code:
m_myDialog->Create(myDialog::IDD, this);
Now, I see my dialog, but I can't set focus on it and can't use it.
What do I have to change in order to host my dialog in my view, and be able to use it and set focus to it, just as part of the view?
Thanks

I know this is a few weeks old, but you need to provide more code or a better context of what is taking place.
I had a similar problem to yourself & found this hard to find info on when I first tried this. Following is an abstract of something I've used. I'm sure there's probably a better way to do this, but I find it works the way I want;
//MyApp.h
class MyDialogClass;
class MyApp : public CWinAppEx
{
public:
MyApp();
virtual BOOL InitInstance();
//code etc
MyDialogClass *p_myDlg;
};
//MyApp.cpp
#include "MyApp.h"
#include "CMyView.h"
#include "mydialogclass.h"
BOOL MyApp::InitInstance()
{
//code etc
p_myDlg = CMyView::GetView()->p_myDlg;
//can be used here or elsewhere. I have mine linked with a button
p_myDlg->ShowWindow(true);
};
//CMyView.h
class MyDialogClass;
class CMyView : public CFormView
{
protected: // create from serialization only
CMyView();
DECLARE_DYNCREATE(CMyView)
public:
enum{ IDD = IDD_CMyView_VIEW };
static CMyView* GetView();
MyDialogClass *p_myDlg;
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
};
//CMyView.cpp
#include "MyApp.h"
#include "CMyView.h"
#include "mydialogclass.h"
int CMyView::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CFormView::OnCreate(lpCreateStruct) == -1)
return -1;
p_myDlg = new MyDialogClass(this);
return 0;
}
void CMyView::DisplayDialogFoo()
{
//can be used here or elsewhere. I have mine linked with a button
p_myDlg->ShowWindow(true);
}
//mydialogclass.h
class MyDialogClass : public CDialog
{
DECLARE_DYNAMIC(MyDialogClass)
public:
MyDialogClass(CWnd* pParent /*= NULL*/);
enum { IDD = IDD_MyDialog_DLG };
};
//mydialogclass.cpp
#include "mydialogclass.h"
MyDialogClass::MyDialogClass(CWnd* pParent /*=NULL*/)
: CDialog(MyDialogClass::IDD, pParent)
{
Create(IDD, pParent);
}
There's also an article here I just found:
http://www.codeproject.com/Articles/1651/Tutorial-Modeless-Dialogs-with-MFC

Related

Getting an error "allocating an object of abstract class type in Juce Framework?

i am new in juce and getting an error like "allocating an object of abstract class type 'CreateAccount'" i am beginner in c++. i am try to call the class from the main window of juce and getting error like this.Below is my code
Main.cpp file
#include <JuceHeader.h>
#include "CreateAccount.h"
//==============================================================================
class TestApplication : public JUCEApplication
{
public:
//==============================================================================
TestApplication() {
}
const String getApplicationName() override {
return "Test";
}
const String getApplicationVersion() override { return "1.0.0"; }
void initialise (const String&) override {
mainWindow.reset (new MainWindow ("Test", new CreateAccount(), *this));
// splash = new SplashScreen("Welcome to Screen!",ImageFileFormat::loadFrom(File("/Resources/bell.png")),
// true);
// splash->deleteAfterDelay(RelativeTime::seconds(5), false);
}
void shutdown() override {
mainWindow = nullptr;
}
private:
class MainWindow : public DocumentWindow
{
public:
MainWindow (const String& name, Component* c, JUCEApplication& a)
: DocumentWindow (name, Desktop::getInstance().getDefaultLookAndFeel()
.findColour (ResizableWindow::backgroundColourId),
DocumentWindow::allButtons),
app (a)
{
setUsingNativeTitleBar (true);
setContentOwned (c, true);
#if JUCE_ANDROID || JUCE_IOS
setFullScreen (true);
#else
setResizable (true, false);
setResizeLimits (300, 250, 10000, 10000);
centreWithSize (getWidth(), getHeight());
#endif
setVisible (true);
}
void closeButtonPressed() override
{
app.systemRequestedQuit();
}
private:
JUCEApplication& app;
//==============================================================================
JUCE_DECLARE_NON_COPYABLE (MainWindow)
};
std::unique_ptr<MainWindow> mainWindow;
};
//==============================================================================
START_JUCE_APPLICATION (TestApplication)
CreateAccount.h file
#include <JuceHeader.h>
//new page for create profile
class CreateAccount : public Component,
public Button::Listener
{
public:
CreateAccount() {
addAndMakeVisible(lblloginwithfb);
lblloginwithfb.setFont(Font(18.0f));
lblloginwithfb.setText("Login with Facebook", dontSendNotification);
lblloginwithfb.setColour(Label::textColourId, Colours::white);
//ready to play button
btncreteprofile.setButtonText("Create your profile");
btncreteprofile.setColour(TextButton::textColourOffId, Colours::white);
btncreteprofile.setColour(TextButton::textColourOnId, Colours::white);
btncreteprofile.setColour(TextButton::buttonColourId, Colour::fromRGB(235,135,15));
btncreteprofile.setColour(TextButton::buttonOnColourId, Colour::fromRGB(235,135,15));
addAndMakeVisible(btncreteprofile);
}
//==============================================================================
void paint(Graphics &g) override {
g.fillAll(Colours::black);
}
void resized() override {
/*Rectangle<int> bounds = getLocalBounds();
FlexBox flexBox;
flexBox.flexDirection = FlexBox::Direction::column;
flexBox.flexWrap = FlexBox::Wrap ::noWrap;
flexBox.alignContent = FlexBox::AlignContent::center;
Array<FlexItem> itemarray;
itemarray.add(FlexItem(80,50,btncreteprofile));
itemarray.add(FlexItem(getWidth(),50,lblloginwithfb));
flexBox.items = itemarray;
flexBox.performLayout(bounds.removeFromBottom(200));*/
Rectangle<int> bounds = getLocalBounds();
const int insetX = getWidth() / 4;
const int insetY = getHeight() / 4;
btncreteprofile.setBounds(insetX,bounds.getCentre().y+80,getWidth() - insetX * 2, 50);
lblloginwithfb.setBounds(insetX,insetY,getWidth() - insetX * 2,getHeight());
}
private:
//==============================================================================
// Your private member variables go here...
Label lblloginwithfb;
TextButton btncreteprofile;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CreateAccount)
};
Please help me when i try to add the listner in createaccount file then will get an error.
You need to implement all pure virtual methods in Button::Listener to make your class not abstract. Button::Listener contains these two methods
virtual void buttonClicked (Button *)=0
virtual void buttonStateChanged (Button *)
The second method is not pure virtual, so you don't have to implement it.
So add a method to your class
virtual void buttonClicked (Button *) override {}
and add the code needed when the button is clicked.
Depending on the C++ version you're using, the override might not get accepted by the compiler. In that case, just omit it. It is used to allow
the compiler to emit warnings/errors with respect to overridden methods.
In JUCE, most UI related things are implemented as a subclass of Component.
Some of the subclasses have the concept of a content component: all subclasses
of ResizableWindow, which adds the setContentOwned() and setContentNonOwned()
methods, inherited by all subclasses of ResizableWindow (especially
DocumentWindow).
To define the content of the DocumentWindow, the example code in your question
uses setContentOwned() in the MainWindow constructor which it gets from the
initialise() in TestApplication.
To implement the navigation you could do the following (there are other ways to do it):
1. Implement the navigation in the MainWindow, so you have the navigation logic in one central place
2. Give each of your "Pages" (let's call one step a Page.) a pointer to the MainWindow. For CreateAccount that would be
CreateAccount.h file:
void setMainWindow(MainWindow * _mainWindow)
{
mainWindow = _mainWindow;
}
3. Add an instance variable, too, somewhere in the CreateAccount class:
MainWindow * mainWindow;
and update the constructor:
CreateAccount()
: mainWindow(nullptr)
{
// ...
}
4. Change the creation code
replace
mainWindow.reset (new MainWindow ("Test", new CreateAccount(), *this));
by:
CreateAccount * ca = new CreateAccount();
MainWindow * mw = new MainWindow ("Test", ca, *this)
ca->setMainWindow(mw);
mainWindow.reset(mw);
5. Implement your navigation in a set of custom methods (need to be public) in MainWindow, e.g.
public:
void createProfileClicked()
{
// ...get entered data...
// ...process entered data...
// ...implement next navigation step...
// (you would create or recycle the "Page" for the next step here)
setContentOwned(
// ...
);
}
6. Call that method from the buttonClicked() event handler in CreateAccount:
mainWindow->createProfileClicked();
This is just one way to implement what you want. It all depends on the complexity of your project.
Edit:
My suggestion given in this answer introduces cyclic dependencies of classes.
Let me first restate what I think you currently have, deduced from your comments:
mainwindow.h
#include "splashpage.h"
class MainWindow : public DocumentWindow
{
public:
// ...
void alaramReadyBtnClicked()
{
setContentOwned(new SplashPage(), false);
}
// ...
};
splashpage.h:
#include "mainwindow.h"
class SplashPage : public Component, public Button::Listener
{
public:
SplashPage()
: mainWindow(nullptr)
{}
void setMainWindow(MainWindow * _mainWindow)
{ mainWindow = _mainWindow; }
void buttonClicked (Button *) override
{
if (button == &tvbtnSomething) {
mainWindow->splashSomethingClicked();
}
}
private:
MainWindow * mainWindow;
};
There's a cyclic dependency of declarations in there between MainWindow and the Page classes. When the compiler sees
mainWindow->splashSomethingClicked();
it needs to have seen the declaration of MainWindow but in mainwindow.h
it needs the declaration of SplashPage for this:
void alaramReadyBtnClicked()
{
setContentOwned(new SplashPage(), false);
}
First, it is good practice to use include guards in your header files
e.g. mainwindow.h
// you need these include guards to prevent that the compiler
// sees this file a second time; it's a very good rule of thumb to always do this
// in you header files
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include "splashpage.h"
class MainWindow : public DocumentWindow
{
// ...
};
#endif // !defined(MAINWINDOW_H)
There are specific situations in C++ for which the compiler doesn't need to know the complete declaration: if you only use pointers or references and don't reference them. You can then use a forward declaration of class names.
But you can't do this with everything in header files only. Because there's a concept of a "compilation unit".
To break the cyclic dependency, change your ...Page.h:
#ifndef SPLASHPAGE_H
#define SPLASHPAGE_H
// don't include mainwindow.h here
class MainWindow; // forward declaration
class SplashPage : public Component, public Button::Listener
{
public:
SplashPage()
: mainWindow(nullptr)
{}
void setMainWindow(MainWindow * _mainWindow)
{
mainWindow = _mainWindow; // pointer copy does not need full declaration
}
// note: implementation not in this header file anymore
void buttonClicked (Button *) override;
private:
// ...
MainWindow * mainWindow; // does not need full declaration
};
#endif // !defined(SPLASHPAGE_H)
splashpage.cpp:
#include "mainwindow.h"
#include "splashpage.h"
void SplashPage::buttonClicked (Button *) override
{
if (button == &tvbtnSomething) {
mainWindow->splashSomethingClicked();
}
}
If you use the JUCE Projucer tool, you can add pairs of these files easily which should already contain the include guards stuff.

Is it possible to use dependency injection with Qt Designer (for .ui files)?

We are developing in C++ (and Qt) using Visual Studio 2015 and the Qt Designer for our UI (via Form / .ui files).
We now need to share some Common Data between our UI elements (e.g. most recently used paths etc.) and I would like to do this via dependency injection (i.e. providing the UI with a Reference to the common object during construction) instead of e.g. (ab)using the singleton pattern.
Has someone faced (and solved) similar problems, and is there a sensible way to do this?
Update (to elaborate):
For example I have a custom FooWidget which I wish to use in my FooDialog.ui form file.
// My custom Widget
class FooWidget : public QWidget {
Q_OBJECT
public:
FooWidget(QWidget* parent);
//...
}
// The FooDialog class (scaffolding created by Qt Designer)
class FooDialog : public QDialog {
Q_OBJECT
public:
FooDialog(QWidget* parent) : QDialog(parent), ui (new Ui::FooDialog()) {
ui->setupUp(this);
//...
}
private:
Ui::FooDialog* ui;
}
// The Ui::FooDialog class autogenerated(!) by Qt Designer
// I cannot (must not) change this code, as it will be regenerated every time
class Ui_FooDialog {
public:
FooWidget* widget;
void setupUi(QWidget *fooDialog) {
//...
widget = new FooWidget(fooDialog);
//...
}
}
namespace Ui { class ScannerStatus: public Ui_ScannerStatus {}; }
I would like to provide the FooWidget with a common data object (e.g. text size and colours shared across all my Ui classes), but I can't do so in the constructor (since the autogenerated Ui_FooDialog treats FooWidget as a generic QWidget, which only needs/takes a QWidget* parent in the constructor - I cannot provide a pointer or reference to my shared TextColourAndSize object.
I am aware I could create a second ui->widget->setupTextColourAndSize(...) step in FooDialog (after the initial ui->setupUi(this)) which provides that common data object, but having two init() type functions seems like a rather bad code smell (one is bad enough).
FooWidget needs two constructors, and a setter for the dependency:
explicit FooWidget(QObject *parent = nullptr) : QWidget(parent), … {
…
}
FooWidget(Dependency *dep, QObject *parent = nullptr) : FooWidget(parent) {
setDependency(dep);
}
void setDependency(Dependency *dep) {
…
}
Then you’d set the dependency after the widget is constructed:
FooDialog(Dependency *dep, …) … {
setupUi(this);
ui->fooWidget->setDependency(dep);
}
This could be automated: the parent widget can have a property that holds the pointer to the dependency, and the child widgets can find it automatically:
FooDialog(Dependency *, …) : … {
setProperty("dependency", dep);
setupUi(this);
}
FooWidget(QWidget *parent) : … {
auto *dep = parent() ? parent()->property("dependency").value<Dependency*>() : nullptr;
if (dep) setDependency(dep);
}
This will work with no extra effort if Dependency derives from QObject. Otherwise, you’ll need to have the following in a suitable header file:
class Dependency { … };
Q_DECLARE_METATYPE(Dependency*)
In all circumstances, you do need to promote the fooWidget object to FooWidget class within Qt Designer.
Ok from what I'm seeing you do not need "dependency injection". Question was incorrectly stated.
You can use this custom widget directly from Qt designer.
When you create your FooDialog place regular widget QWidget in place where you need to have a FooWidget.
Then "promote" regular this widget to FooWidget (possibly you have to add some simple information about that type) - (I did that long time ago and do not remember all details).
For detailed instruction just google: qt promote widget qt designer, you will find lots of examples how to do it.
These were good solutions, but talking about dependency injections, there is also an option to have some fun with C++. It's not a wise solution at all, of course I know it, but nevertheless...
foowidget.h
#ifndef FOOWIDGET_H
#define FOOWIDGET_H
#include <QWidget>
class Something
{
public:
QString getHello() const
{ return "Hello world!"; }
};
/***************************************************/
template<typename T>
class Injector
{
public:
QString getHello() const
{ return m_dataContainer.getHello(); }
private:
T m_dataContainer;
};
/***************************************************/
class FooWidget : public QWidget, public Injector<Something>
{
Q_OBJECT
public:
explicit FooWidget(QWidget* parent = nullptr);
protected:
virtual void mousePressEvent(QMouseEvent*) override;
};
#endif // FOOWIDGET_H
foowidget.cpp
#include "foowidget.h"
#include <QMessageBox>
FooWidget::FooWidget(QWidget *parent)
: QWidget(parent)
{ }
void FooWidget::mousePressEvent(QMouseEvent*)
{
QMessageBox::information(nullptr, "Test", getHello());
}
foodialog.h
#ifndef FOODIALOG_H
#define FOODIALOG_H
#include <QDialog>
class SomethingElse
{
public:
QString getHello() const
{ return "OMG! OMG"; }
};
#include "foowidget.h"
namespace Ui {
class FooDialog;
}
class FooDialog : public QDialog, public Injector<SomethingElse>
{
Q_OBJECT
public:
explicit FooDialog(QWidget *parent = nullptr);
~FooDialog();
protected:
void showEvent(QShowEvent *) override;
private:
QScopedPointer<Ui::FooDialog> ui;
};
#endif // FOODIALOG_H
foodialog.cpp
#include "foodialog.h"
#include "ui_foodialog.h"
#include <QMessageBox>
FooDialog::FooDialog(QWidget *parent)
: QDialog(parent)
, ui(new Ui::FooDialog)
{
ui->setupUi(this);
}
FooDialog::~FooDialog()
{ }
void FooDialog::showEvent(QShowEvent *)
{
QMessageBox::information(nullptr, "Test", getHello());
}
Multiple inheritance + deriving widgets from some small template proxy class works for both custom widgets and those, having UI forms. I've put a FooWidget on a FooDialog (via propagation mechanizm) in the sketch above and got two message boxes.
The idea itself can be implemented better, with smarter template usage, just tried to reduce sample code, anyway it's an unnessesary complication. But technically it works without any additional initializations =)

How to access to variable on parent class mfc

I have a Dialog on MFC application.
MyDialog :
{
int variable1;
int variable2;
Class1 cls = new Class1();
}
And in class1()
Class1()
{
void Function1()
void Function2()
}
--
So How to Access and return to variable1 in Class1::Function1()
Class1::Function1()
{
MyDialog dlg = new MyDialog ();
Get x = dlg->variable1; //if like this, variable1 alway=0, because in above line, i'm define new myDialog()
}
I think to delegate on .NET but in MFC application, I can't get it done ?
You can
"extend" your constructor, by adding a pointer to the parent in your child dialog and access your variable or call public functions (requires header of parent)
use SendMessage and handle the messages in your parent dialog
use GetParent in-place and dynamic_cast it to your parent dialog (requires header of parent)
1.
Class1::Class1(MyParent *parent)
{
m_parentPointer = parent;
}
void Class1::Function1(void)
{
m_parentPointer->myPublicVariable;
}
2.
void Class1::Function1(void)
{
CWnd *parent = GetParent();
if (parent)
parent->SendMessage(WM_YOUR_MESSAGE, yourWPARAM, yourLPARAM);
}
//MessageMap of parent
ON_MESSAGE(WM_YOUR_MESSAGE, ParentClassHandler)
LRESULT Parent::ParentClassHandler(WPARAM wp, LPARAM lp)
{
//Process
}
3.
void Class1::Function1(void)
{
CWnd *parent = GetParent();
if (parent)
{
Parent *p = dynamic_cast<Parent*>(parent);
if (p)
{
//Process
}
}
}
If Class1::Function1() needs to access the dialog, then you need a pointer to the dialog in Function1.
void Class1::Function1(MyDialog *dlg) {
}
If you want to store the dialog pointer permanently, then adjust the constructor of Class1.
class Class1 {
public:
Class1(class MyDialog *dlg_) : dlg(dlg_) {}
class MyDialog *dlg;
}
Another, probably better, way to implement it, is to move the code that needs to access Class1 and MyDialog into global functions or into MyDialog member functions. But which way to go depends on what the classes do and which design you want.
You have to start with basic C++ classes before diving in to this. But here is how it's done:
MyDialog dlg = new MyDialog ();
dlg->variable1 = 1; //set the variable
if (IDOK == dlg->DoModal()) //wait for user to click OK
{
int x = dlg->variable1; //get the variable
}
However, dlg->variable1 is not changed unless you drive your own class and do something to change it.
For example, you can use Dialog Data Exchange to assign variable1 to a check box.
void MyDialog::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Check(pDX, IDC_CHECK1, variable1);
}
To try it, use Visual Studio's dialog wizard to create a check box and an edit box. It will probably create check box with resource id IDC_CHECK1, an edit box with resource id set to IDC_EDIT1.
Another option:
use OnInitDialog to assign variable to dialog controls
use OnOK() to get variables from dialog controls:
:
BOOL MyDialog::OnInitDialog()
{
//put `CString m_string1;` in class declaration
BOOL result = CDialog::OnInitDialog();
SetDlgItemText(IDC_EDIT1, m_string1);
return result;
}
void MyDialog::OnOK()
{
GetDlgItemText(IDC_EDIT1, m_string1);
CDialog::OnOK();
}

How to add images when creating Visual C++ MFC project from scratch?

I am try to create very simple c++ MFC project. Since it is very simple one I need to create it form scratch.
my code so far is shown below. But now I need to add picture control and thus my Intent use CImage class. But to use CImage class I need to add altimage.h header to my project. But When I do so it gives a error that cannot open source file altimage.h. So
How can I overcome this problem.
How to add the file I needed when I creating the MFC projects form the scratch.
please help me solvethis.
thanks
#include <afxwin.h> //MFC core and standard components
//#include <altimage>
#include "resource.h" //main symbols
//-----------------------------------------------------------------------------------------
//Globals
//CEdit * TEST;
CEdit * RECOG_CHARS;
CButton * BTN_CONVERT;
CButton * BTN_QUIT;
CStatic * IMG_IMAGE;
class HWCR_FORM : public CDialog
{
public:
HWCR_FORM(CWnd* pParent = NULL) : CDialog(HWCR_FORM::IDD, pParent)
{ }
// Dialog Data, name of dialog form
enum{ IDD = ID_MAIN_INTERFACE };
protected:
virtual void DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); }
//Called right after constructor. Initialize things here.
virtual BOOL OnInitDialog()
{
CDialog::OnInitDialog();
RECOG_CHARS = (CEdit *)GetDlgItem(CE_ID_TEXT);
BTN_CONVERT = (CButton *)GetDlgItem(CB_ID_START);
BTN_QUIT = (CButton *)GetDlgItem(CB_ID_QUIT);
IMG_IMAGE = (CStatic *)GetDlgItem(CS_ID_IMAGE);
HBITMAP image = (HBITMAP)LoadImage(NULL,L"C:\\Users\\Kasun\\Desktop\\image.bmp",IMAGE_BITMAP,150,120,LR_LOADFROMFILE);
IMG_IMAGE->SetBitmap(image);
RECOG_CHARS->SetWindowTextW(L"Hi there");
return true;
}
public:
DECLARE_MESSAGE_MAP()
};
//-----------------------------------------------------------------------------------------
class HWCR : public CWinApp
{
public:
HWCR() { }
public:
virtual BOOL InitInstance()
{
CWinApp::InitInstance();
SetRegistryKey(_T("Hills Of Darkness"));
HWCR_FORM dlg;
m_pMainWnd = &dlg;
INT_PTR nResponse = dlg.DoModal();
return FALSE;
} //close function
};
//-----------------------------------------------------------------------------------------
//Need a Message Map Macro for both CDialog and CWinApp
BEGIN_MESSAGE_MAP(HWCR_FORM, CDialog)
END_MESSAGE_MAP()
//-----------------------------------------------------------------------------------------
HWCR theApp;
First at all, in order to use CImage, you need to include header file
#include <atlimage.h>
instead of
#include <altimage>
Secondly, be sure that this file's directory is included into MSVC paths...
Normally it should be included as this header file is part of MFC / Win32 SDK....check the directories in VS properties.
Z.

Adding new functionality to a class

I'm studying the Qt4 library and I want to add some functionality to all the children of QWidget in my project. I need all widgets to have mousePressEvent overridden. Obviously I do not need to override it in every particular widget I use(I use many of them and I they to follow DRY rule) , instead I create a Foo class:
class Foo : public QWidget
{
Q_OBJECT
protected:
/* implementation is just a test */
virtual void mousePressEvent(QMouseEvent*) { this->move(0,0); }
};
And derive my button from it:
class FooButton : public QPushButton , public Foo
{
public:
FooButton (QWidget* parent) : QPushButton(parent) { };
};
But the event seems to be not overridden... What am I doing wrong?
Thanks in advance.
For the mousePressEvent access, try QObject::installEventFilter().
http://doc.qt.digia.com/stable/qobject.html
You are inheriting twice now from QWidget. This is problematic (see diamond problem).
Instead, drop your Foo class and move your custom mouse press event handler to your FooButton class:
class FooButton : public QPushButton
{
Q_OBJECT
protected:
/* implementation is just a test */
virtual void mousePressEvent(QMouseEvent*) { this->move(0,0); }
public:
FooButton (QWidget* parent) : QPushButton(parent) { };
};
If this doesn't suit the design of your application, then try using virtual inheritance instead. That is, change Foo to:
class Foo : public virtual QWidget
If that doesn't help, you should follow the advice of the other answers and install an event handler.
(You can read about virtual inheritance in its Wikipedia article.)
I suspect that the problem is that you're inheriting from QWidget twice, once through QPushButton and once through Foo.
From the way you phrased the question, I'm assuming that you want to do this for varying kinds of widgets, and thus don't want to have to subclass QPushButton, QLabel, QCheckBox, etc. If this is not the case then you should use Nikos's answer.
If not, your best bet is probably doing to be to use an event filter.
class MousePressFilter : public QObject {
Q_OBJECT
public:
MousePressFilter(QObject *parent) : QObject(parent) { }
protected:
bool eventFilter(QObject *watched, QEvent *event) {
QWidget *widget = dynamic_cast<QWidget*>(watched);
widget->move(0,0);
return false;
}
};
And then in your Foo class constructor:
class Foo {
Foo() {
installEventFilter( new MousePressFilter(this) );
}
};