Witam,
Piszę program, który będzie dobierał dane z sieci i je rysował(i tak w kółko). Odbieranie i rysowanie chcę zrobić w wątku.
Trochę jest bałagan w kodzie, ale już wszystkiego próbuje:
oscthread.h
#ifndef OSCTHREAD_H
#define OSCTHREAD_H
#include <QThread>
#include <QGraphicsScene>
#include <QMutex>
class OscThread : public QThread
{
Q_OBJECT
private:
QGraphicsScene * scene;
QMutex mutex;
void draw(struct osc_t * osc, unsigned int n);
public:
explicit OscThread(QGraphicsScene * s, QObject *parent = 0);
QGraphicsScene * getScene(){ return this->scene; }
protected:
void run();
signals:
public slots:
};
struct osc_t{
unsigned int time;
unsigned int port[3];
};
#endif // OSCTHREAD_H
oscthread.cpp
#include "oscthread.h"
OscThread::OscThread(QGraphicsScene * s, QObject *parent) :
QThread(parent)
{
//scene = new QGraphicsScene(this);
scene = s;//new QGraphicsScene(0, 0, 320, 240);
//scene->setSceneRect(0, 0, 320, 240);
scene->addRect(100, 100, 200, 200);
}
void OscThread::draw(struct osc_t * osc, unsigned int n){
scene->clear();
int x;
for(x=1; x<200; x++){
scene->addLine(x, x, x+5, x+5); /* wykres będzie rysowany liniami - tutaj test */
}
}
void OscThread::run(){
// mutex.lock();
//scene->advance();
for(;;){
// mutex.unlock();
draw(0/* narazie nic*/, 0);
// scene->addLine(5, 5, 10, 10);
sleep(1);/* tymczasowo */
// mutex.lock();
}
}
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
scene = new QGraphicsScene();
ui->graphicsView->setScene(this->scene);
osc = new OscThread(scene, this);
//ui->graphicsView->setScene(osc->getScene());
//osc->setScene(scene);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
osc->start();
}
Efekt mam ciągle ten sam, czasami się rysuje po włączeniu programu, czasami nie, program się wysypuje itp. To zapewne problem połączenia QGraphicsScene + QThread. Jak zmusić program do prawidłowego działania?
Linux, QTCreator 2.0.1(Qt 4.7.0)