• 4659阅读
  • 2回复

问一个最基本的 QT线程 和 类成员 之间的问题 [复制链接]

上一主题 下一主题
离线wang0921jun
 
只看楼主 倒序阅读 楼主  发表于: 2011-05-03
— 本帖被 XChinux 从 Qt基础编程 移动到本区(2011-05-05) —
        以下是一个最基本的QT线程应用程序,就是让线程打印20次PING字符串。
    我的问题是:怎么让QT线程可以访问hello类中的成员呢,比如说在线程里,给button设置一下按钮文字。如果用类成员函数就很好实现了,在构造的时候用button->setText(“退出”)就可以了。

//////////////////////////////////////////////////////////////////////    hello.cpp    ////////////////////////////////////////////////////////////////////////////////

#include "hello.h"
#include <qpushbutton.h>

hello::hello( QWidget* parent,  const char* name, WFlags fl )  : helloBase( parent, name, fl )
{
    button = new QPushbutton;
    a.start();

    
    connect(button, SIGNAL(clicked()), this, SLOT(goodBye()));
}

hello::~hello()
{
}

void hello::goodBye()
{
    close();
}

void MyThreadA::run()
{
    for(int count=0;count<20;count++)
    {
        sleep(1);
        qDebug("Ping!");
    }
}

//////////////////////////////////////////////////////////////////////    hello.h    ////////////////////////////////////////////////////////////////////////////////
#ifndef HELLO_H
#define HELLO_H
#include "hellobase.h"
#include <qthread.h>
#include <qpushbutton.h>

class MyThreadA : public QThread
{
public:
    virtual void run();
};

class hello : public helloBase
{
    Q_OBJECT

public:
    MyThreadA a;
    hello( QWidget* parent = 0, const char* name = 0, WFlags fl = 0 );
    QPushbutton *button;

    ~hello();

private slots:
    void goodBye();
};
#endif // HELLO_H

//////////////////////////////////////////////////////////////////////    mani.cpp    ////////////////////////////////////////////////////////////////////////////////

#include "hello.h"
//#include <qpe/qpeapplication.h>
#include <qapplication.h>
hello *mw;

int main( int argc, char ** argv )
{
//    QPEApplication a( argc, argv );
    QApplication a( argc, argv );

    mw = new hello;
    a.setMainWidget(&;mw);
    mw.show();

    return a.exec();
}
离线wxj120bw

只看该作者 1楼 发表于: 2011-05-04
考虑下qt信号和槽机制
离线米尔利安

只看该作者 2楼 发表于: 2011-05-04
只有主线程可以设置GUI界面内容的改变。但是子线程可以读取GUI的内容。
在主线程里做一个槽函数,里面填上你要对界面进行的操作。在子线程里定义对应的信号,然后把信号和槽连起来。子线程执行完毕之后发射该信号。让主线程对界面进行操作。
我们在天上的父,愿人都尊你的名为圣。
愿你的国降临。
愿你的旨意行在地上,如同行在天上。
快速回复
限100 字节
 
上一个 下一个