Qt,两个QWidget对象之间的简单连接
Posted
技术标签:
【中文标题】Qt,两个QWidget对象之间的简单连接【英文标题】:Qt, a simple connection between two QWidget objects 【发布时间】:2013-02-27 12:04:42 【问题描述】:我有一个继承自 QMainWindow 的类和两个继承自 QWidget 的类。我将这两个 QWidget 对象添加到我的 QMainWindow 对象中,并且我想在这两个 QWidget 对象之间创建一个连接(其中一个包含 QPushButton 对象)。不幸的是,不想工作......
代码:
主机:
#ifndef MAINFRAME_H
#define MAINFRAME_H
#include <QtGui/QMainWindow>
#include "DrawComponent.h"
#include "ControllComponent.h"
class MainFrame : public QMainWindow
Q_OBJECT
public:
DrawComponent *dComponent;
ControllComponent *cComponent;
MainFrame();
;
#endif
#include "MainFrame.h"
#include "DrawComponent.h"
#include "ControllComponent.h"
#include <iostream>
using namespace std;
MainFrame :: MainFrame()
this->setGeometry(100, 100, 640, 480);
this->dComponent = new DrawComponent(this);
this->cComponent = new ControllComponent(this);
QObject::connect(this->cComponent->rysuj1, SIGNAL(clicked()), this, SLOT(dComponent->draw1));
FIRST QWidget 类
#ifndef DRAWCOMPONENT_H
#define DRAWCOMPONENT_H
#include <QtGui/QMainWindow>
#include <qwidget.h>
class DrawComponent : public QWidget
Q_OBJECT
public:
DrawComponent(QMainWindow *parent);
public slots:
void draw1();
;
#endif
#include "DrawComponent.h"
#include <qpushbutton.h>
#include <qgridlayout.h>
using namespace std;
DrawComponent :: DrawComponent(QMainWindow *parent)
this->setParent(parent);
this->setGeometry(0, 0, 500, 480);
QPalette p(palette());
p.setColor(QPalette::Background, Qt::black);
this->setPalette(p);
this->setAutoFillBackground(true);
this->show();
void DrawComponent :: draw1()
QPalette p(palette());
p.setColor(QPalette::Background, Qt::blue);
this->setPalette(p);
第二个 QWidget 类
#ifndef CONTROLLCOMPONENT_H
#define CONTROLLCOMPONENT_H
#include <QtGui/QMainWindow>
#include <qwidget.h>
#include <qpushbutton.h>
class ControllComponent : public QWidget
Q_OBJECT
public:
QPushButton *rysuj1;
ControllComponent(QMainWindow *parent);
;
#endif
#include "ControllComponent.h"
#include <qpushbutton.h>
#include <qgridlayout.h>
ControllComponent :: ControllComponent(QMainWindow *parent)
this->setParent(parent);
this->setGeometry(500, 0, 140, 480);
QPalette p(palette());
p.setColor(QPalette::Background, Qt::red);
this->setPalette(p);
this->setAutoFillBackground(true);
this->rysuj1 = new QPushButton(tr("draw1"), this);
this->rysuj1->setGeometry(45, 10, 50, 50);
this->rysuj1->show();
this->show();
【问题讨论】:
【参考方案1】:您调用将来自rysuj1
的clicked()
信号连接到dComponent
的draw1()
插槽
QObject::connect(this->cComponent->rysuj1, SIGNAL(clicked()),
this, SLOT(dComponent->draw1));
需要
QObject::connect(this->cComponent->rysuj1, SIGNAL(clicked()),
dComponent, SLOT(draw1()));
【讨论】:
【参考方案2】:dComponent->draw1
不是槽
看这里:
QObject::connect(&a, SIGNAL(valueChanged(int)),
&b, SLOT(setValue(int)));
参数:1. 对象,2. 信号函数,3. 对象,4. 槽函数。
所以
QObject::connect(this->cComponent->rysuj1, SIGNAL(clicked()), dComponent, SLOT(draw1()));
【讨论】:
以上是关于Qt,两个QWidget对象之间的简单连接的主要内容,如果未能解决你的问题,请参考以下文章
将 Qt Widgets 和 QML 与 QWidget::createWindowContainer() 结合起来