简单的QT进程间通信QCOP(2)

来源:互联网 发布:华为工业级网络路由器 编辑:程序博客网 时间:2024/06/05 11:27
 //Cel.h //子程序1的头文件

#ifndef CEL_H

#define CEL_H

#include <QWidget>

class QSlider;

class QHBoxLayout;

class Cel : public QWidget

{

    Q_OBJECT

   

public:

    Cel();

    ~Cel() {};

private slots:

    void handleMsg(const QString &message, const QByteArray &data);

    void sendMsg(int celNum);     //槽

private:

    void fahToCel(int fahNum);

    void createScreen();

    void createCel();

    void listenChannel();

    QSlider* slider;

    QHBoxLayout* celLayout;

};

//Cel.cpp

#endif //CEL_H

#include <QPushButton>

#include <QSlider>

#include <QLabel>

#include <QLCDNumber>

#include <QVBoxLayout>

#include <QHBoxLayout>

#include <QApplication>

#include <QCopChannel>

#include <QDataStream>

#include <QByteArray>

#include "Cel.h"

Cel::Cel() : QWidget()

{

    createScreen();

    listenChannel();

}

void Cel::createScreen()

{

    QPushButton* quitBtn = new QPushButton("Quit");

    createCel();

    QVBoxLayout *mainLayout = new QVBoxLayout;

    mainLayout->addWidget(quitBtn);

    mainLayout->addLayout(celLayout);

    setLayout(mainLayout);

    slider->setFocus();

   

    connect(quitBtn, SIGNAL(clicked()), qApp, SLOT(quit()));

    setWindowTitle("Celsius");

}

void Cel::createCel()

{

    slider = new QSlider(Qt::Vertical);

    slider->setRange(0, 100);

    slider->setValue(0);

    slider->setTickPosition(QSlider::TicksLeft);

   

    QLabel* celLabel = new QLabel("0");

   

    celLayout = new QHBoxLayout;

    celLayout->addWidget(celLabel, 0, Qt::AlignRight);

    celLayout->addWidget(slider, 0, Qt::AlignLeft);   

    celLayout->setSpacing(10);

    connect(slider, SIGNAL(valueChanged(int)), celLabel, SLOT(setNum(int)));

    connect(slider, SIGNAL(valueChanged(int)), this, SLOT(sendMsg(int)));

}

void Cel::fahToCel(int fahNum)

{

    int celNum = (fahNum - 32) * 5 / 9;

    slider->setValue(celNum);

}

void Cel::listenChannel()

{

    QCopChannel *channel = new QCopChannel("/System/Temperature", this);//注册Channel

    connect(channel, SIGNAL(received(const QString &, const QByteArray &)),

            this, SLOT(handleMsg(const QString &, const QByteArray &)));

}

void Cel::handleMsg(const QString &message, const QByteArray &data)//处理收到信息

{

    QDataStream in(data);

   

    if (message == "ConvertFahToCel(int)")

    {

        int fahNum;

        in >> fahNum;

        fahToCel(fahNum);

    }

}

void Cel::sendMsg(int celNum) //发送信息

{

    QByteArray data;

    QDataStream out(&data, QIODevice::WriteOnly);

  out << celNum;

    QCopChannel::send("/System/Temperature", "ConvertCelToFah(int)", data);

}

#include <QApplication>

#include "Cel.h"

int main(int argc, char *argv[])

{

    QApplication app(argc, argv/*, QApplication::GuiClient*/);

    Cel screen;

    screen.setGeometry(0, 25, 100, 250);

    screen.show();

    return app.exec();

}