C++ - QMediaPlayer emits no sound - c++
I'm trying to make a simple synth using Qt. A note is supposed to play when you left click a key but no sound is played. I've tried to search for a solution to the problem but I haven't found anything that helps.
Since I'm fairly new to Qt I believe that the problem is that I lack full understanding of how the framework works but I simply can't figure out why the sound wont play.
I've managed to emit sounds from the main.cpp and have included examples further down in the code when a sound is played and when it isn't.
Hope I've presented my problem well and thanks in advance.
//key.h
#ifndef KEY_H
#define KEY_H
#include <QGraphicsRectItem>
#include <QObject>
#include <QKeyEvent>
#include <QGraphicsSceneMouseEvent>
#include <QDebug>
#include <QBrush>
#include <QMediaPlayer>
enum Tune {A, B, C, D, E, F, G, ASS, BESS, DESS, ESS, GESS, MUTE}; // Key tune
class Key : public QObject, public QGraphicsRectItem {
Q_OBJECT
public:
Key(Tune t=MUTE);
void mousePressEvent(QGraphicsSceneMouseEvent *event);
void mouseMoveEvent(QGraphicsSceneMouseEvent *event);
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
void paintPlayedKey();
void resetPaintedKey();
void setTone();
QMediaPlayer* getTone() {return tone;}
Tune getTune() {return tune;}
private:
Tune tune;
QMediaPlayer *tone;
};
#endif // KEY_H
//key.cpp
#include "key.h"
void Key::paintPlayedKey()
{
this->setBrush(* new QBrush(Qt::blue));
}
void Key::resetPaintedKey()
{
if(tune < 7)
this->setBrush(* new QBrush(Qt::white));
else
this->setBrush(* new QBrush(Qt::black));
}
void Key::setTone() // Sets sounds to tune
{
if(tune == 0)
tone->setMedia(QUrl("qrc:/keys/Pianosounds/TheKeys/a.wav"));
else if (tune == 1)
tone->setMedia(QUrl("qrc:/keys/Pianosounds/TheKeys/b.wav"));
else if (tune == 2)
tone->setMedia(QUrl("qrc:/keys/Pianosounds/TheKeys/c.wav"));
else if (tune == 3)
tone->setMedia(QUrl("qrc:/keys/Pianosounds/TheKeys/d.wav"));
else if (tune == 4)
tone->setMedia(QUrl("qrc:/keys/Pianosounds/TheKeys/e.wav"));
else if (tune == 5)
tone->setMedia(QUrl("qrc:/keys/Pianosounds/TheKeys/f.wav"));
else if (tune == 6)
tone->setMedia(QUrl("qrc:/keys/Pianosounds/TheKeys/g.wav"));
else if (tune == 7)
tone->setMedia(QUrl("qrc:/keys/Pianosounds/TheKeys/ab.wav"));
else if (tune == 8)
tone->setMedia(QUrl("qrc:/keys/Pianosounds/TheKeys/bb.wav"));
else if (tune == 9)
tone->setMedia(QUrl("qrc:/keys/Pianosounds/TheKeys/db.wav"));
else if (tune == 10)
tone->setMedia(QUrl("qrc:/keys/Pianosounds/TheKeys/eb.wav"));
else if (tune == 11)
tone->setMedia(QUrl("qrc:/keys/Pianosounds/TheKeys/gb.wav"));
}
Key::Key(Tune t)
{
tune = t;
tone = new QMediaPlayer();
setTone();
}
void Key::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
//Not sure if we wanna do anything here
}
void Key::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
//play tune
if (event->buttons() == Qt::LeftButton) {
qDebug() << "Pressed";
paintPlayedKey();
if(tone->state() == QMediaPlayer::PlayingState) {
tone->setPosition(0);
qDebug() << "Have played?";
}
else if (tone->state() == QMediaPlayer::StoppedState) {
qDebug() << "Should play?"; // Well it doesn't :-)
tone->play();
}
}
}
void Key::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
//stop playing tune
resetPaintedKey();
tone->stop();
}
//main.cpp
#include <QApplication>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QBrush>
#include <QMediaPlayer>
#include <QTimer>
#include <iostream>
#include <vector>
#include "mainwindow.h"
#include "key.h"
using namespace std;
const int W_KEY_H = 150; // White Key width and height
const int W_KEY_W = 50;
const double B_KEY_H = 150 * 2/3; // White Key width and height
const double B_KEY_W = 50/2;
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
// create a scene
QGraphicsScene *scene = new QGraphicsScene();
// Create white keys of synth
Tune a = A, b = B, c = C, d = D, e = E, f = F, g = G;
Key *a1 = new Key(a);
Key *b1 = new Key(b);
Key *c1 = new Key(c);
Key *d1 = new Key(d);
Key *e1 = new Key(e);
Key *f1 = new Key(f);
Key *g1 = new Key(g);
vector<Key*> whites = {a1, b1, c1, d1, e1, f1, g1};
int x = 0;
for(int i = 0; i < whites.size(); i++, x+=W_KEY_W)
whites[i]->setRect(x, 0, W_KEY_W, W_KEY_H);
// add the keys to the scene
for(int i = 0; i < whites.size(); i++)
scene->addItem(whites[i]);
// focus keys
for(int i = 0; i < whites.size(); i++) {
whites[i]->setFlag(QGraphicsItem::ItemIsFocusable);
whites[i]->setFocus();
}
// Create black keys of synth
Tune ass = ASS, bess = BESS, dess = DESS, ess = ESS, gess = GESS;
Key *ass1 = new Key(ass);
Key *bess1 = new Key(bess);
Key *dess1 = new Key(dess);
Key *ess1 = new Key(ess);
Key *gess1 = new Key(gess);
Key *ass2 = new Key(ass);
vector<Key*> blacks = {ass1, bess1, dess1, ess1, gess1, ass2};
// For now...
ass1->setRect(a1->rect().x() - B_KEY_W/(double)2, 0, B_KEY_W, B_KEY_H);
bess1->setRect(b1->rect().x() - B_KEY_W/(double)2, 0, B_KEY_W, B_KEY_H);
dess1->setRect(d1->rect().x() - B_KEY_W/(double)2, 0, B_KEY_W, B_KEY_H);
ess1->setRect(e1->rect().x() - B_KEY_W/(double)2, 0, B_KEY_W, B_KEY_H);
gess1->setRect(g1->rect().x() - B_KEY_W/(double)2, 0, B_KEY_W, B_KEY_H);
ass2->setRect(g1->rect().x() + g1->rect().width() - B_KEY_W/(double)2, 0, B_KEY_W, B_KEY_H); // Nödlösning
//paint
for(int i=0; i<blacks.size(); i++)
blacks[i]->setBrush(* new QBrush(Qt::black));
// add the keys to the scene
for(int i = 0; i < blacks.size(); i++)
scene->addItem(blacks[i]);
// focus keys
for(int i = 0; i < blacks.size(); i++) {
blacks[i]->setFlag(QGraphicsItem::ItemIsFocusable);
blacks[i]->setFocus();
}
// add a view
QGraphicsView *view = new QGraphicsView(scene);
//show view
view->show();
//view->setFixedSize(800, 600);
//scene->setSceneRect(0, 0, 800, 600);
// Sound plays
QMediaPlayer *test = new QMediaPlayer();
test->setMedia(QUrl("qrc:/sounds/Pianosounds/TheKeys/a.wav"));
test->play();
// doesn't play
c1->getTone()->play();
return app.exec();
}
Related
QT real time graph has flickering problem
i am using openglseris (line) to display incoming data. i edited the opengl series example given by the qt as per my needs. How can I update the openglseris without flickering the display (smooth data update)? Because so far I have managed to display incoming data but the display is flickering every time it updates the value. //***********datasource.h**********// #ifndef DATASOURCE_H #define DATASOURCE_H #include <QtCore/QObject> #include <QtCharts/QXYSeries> #include <QtWidgets/QLabel> #include <QtCore/QElapsedTimer> #include <QtCore/QTimer> QT_CHARTS_USE_NAMESPACE class DataSource : public QObject { Q_OBJECT public: explicit DataSource(QObject *parent = 0); void startUpdates(const QList<QXYSeries *> &seriesList, QLabel *fpsLabel); public slots: void generateData(int seriesCount, int rowCount, int colCount); void update(QAbstractSeries *series, int seriesIndex); void handleSceneChanged(); void updateAllSeries(); private: QVector<QVector<QVector<QPointF> > > m_data; int m_index; QList<QXYSeries *> m_seriesList; QLabel *m_fpsLabel; QElapsedTimer m_fpsTimer; QTimer m_dataUpdater; }; #endif // DATASOURCE_H //*************datasource.cpp*******************// #include "datasource.h" #include <QtCore/QtMath> #include<QDebug> QT_CHARTS_USE_NAMESPACE int shift=0; int c[2048]={50,149,143,148,151,151,150,150,149,149,152,148,148,147,146,152,149,150,147,151,150,149,148,149,152,150,148,150,147,149,149,149,149,151,152,151,149,148,151,147,151,147,150,147,151,150,154,150,151,151,151,151,154,154,150,152,148,151,150,148,150,151,149,151,150,156,155,159,158,154,154,151,152,154,155,150,154,149,150,149,154,152,155,150,154,152,155,150,149,154,150,156,154,150,151,150,151,155,151,157,151,152,150,151,148,150,150,157,150,156,150,147,155,150,155,155,152,150,154,151,152,151,150,152,151,157,151,152,150,149,154,152,154,154,151,151,150,150,157,154,154,155,150,155,157,150,152,151,156,151,150,152,152,154,155,150,155,150,150,156,154,149,152,154,154,154,151,150,156,148,150,157,150,154,150,154,154,154,156,150,150,155,156,155,156,154,154,150,154,155,158,151,154,154,150,150,156,151,148,150,151,150,154,150,156,150,154,151,154,150,150,157,154,155,154,157,155,156,152,155,155,157,154,159,156,156,154,155,154,156,156,151,152,150,150,156,154,152,159,150,150,158,150,155,156,155,156,155,155,154,154,154,155,155,155,154,149,156,150,156,150,155,155,156,157,150,157,157,151,157,157,158,152,150,156,155,154,154,155,156,154,154,156,150,157,154,150,157,157,152,155,155,154,154,155,154,156,156,150,155,154,157,155,156,156,150,155,157,154,157,154,161,155,155,155,158,156,156,150,154,155,155,157,157,157,152,155,156,159,155,154,154,155,157,151,159,154,157,154,157,158,154,155,155,155,159,155,156,156,157,154,158,155,160,157,157,158,158,155,158,155,155,155,150,159,156,157,158,156,157,156,154,156,158,157,156,159,156,157,158,155,157,154,157,155,157,156,157,157,159,156,157,156,162,158,155,159,156,156,159,155,157,155,158,155,162,156,157,154,163,157,158,156,161,157,156,157,156,154,158,159,160,156,159,159,157,159,155,162,159,156,155,157,154,155,156,157,156,157,155,159,157,160,150,157,158,152,157,155,154,158,155,158,158,158,155,158,156,156,157,159,156,159,156,157,157,156,156,158,155,155,160,150,158,154,159,157,154,157,155,157,159,154,157,150,155,155,155,152,155,159,158,155,155,158,156,154,154,155,157,157,154,158,155,159,155,160,156,159,157,155,150,160,156,150,154,157,150,158,155,150,154,157,155,158,160,158,154,159,157,157,157,155,156,159,154,157,160,154,155,157,156,150,156,157,156,158,150,156,156,154,157,156,159,158,158,156,155,156,155,156,155,160,155,156,158,157,154,150,158,157,155,157,155,158,156,159,156,157,159,157,156,157,159,154,160,158,158,160,156,155,154,161,159,160,157,156,154,155,154,156,159,158,155,154,150,158,162,156,156,155,154,160,159,162,160,159,158,161,150,159,156,155,160,158,159,158,155,161,155,157,154,154,156,150,156,163,154,149,160,160,155,159,155,156,155,150,157,158,157,157,154,157,155,158,155,156,156,156,155,150,156,157,155,155,155,157,157,157,157,155,157,157,155,159,158,150,156,157,155,158,156,158,155,154,157,157,156,155,156,155,160,157,159,150,158,155,162,157,159,159,155,156,154,155,158,157,161,156,158,157,155,156,158,158,157,156,158,157,154,155,150,158,156,160,160,160,156,157,154,155,150,159,156,152,156,160,158,157,154,158,158,158,155,156,160,160,155,156,157,158,157,159,157,161,155,152,157,158,154,157,160,156,158,155,158,158,156,155,155,150,154,156,155,158,155,155,157,156,158,154,155,158,162,156,159,158,157,159,154,155,160,157,158,154,155,157,158,159,158,158,157,155,156,159,159,155,155,158,155,155,158,155,160,161,157,159,159,156,155,150,156,155,150,156,157,155,155,158,155,156,159,156,158,162,155,160,154,158,158,158,157,160,156,155,157,152,156,160,158,160,155,158,155,155,157,155,156,159,154,155,157,157,160,159,156,157,162,158,156,157,154,160,157,156,159,159,156,155,159,158,157,156,162,160,158,157,162,157,158,157,157,163,156,156,160,161,154,155,156,159,157,156,158,159,157,155,157,162,157,160,158,159,155,156,155,160,158,157,155,160,159,156,157,157,160,155,157,158,157,157,156,160,155,157,156,157,159,159,160,159,160,157,162,157,157,154,157,157,159,161,155,160,155,155,157,160,156,158,158,161,159,156,156,158,160,160,158,155,157,161,154,160,156,155,156,160,158,156,157,150,155,154,160,157,154,155,155,160,155,154,158,157,155,160,155,156,160,154,157,154,158,157,159,157,155,152,155,156,156,155,155,155,155,156,156,159,159,157,160,155,158,158,157,157,150,155,156,155,156,156,155,159,150,161,155,159,156,156,158,161,155,157,156,159,155,150,155,156,161,155,156,156,154,157,155,157,158,156,158,160,155,161,158,156,159,157,156,159,155,158,162,155,160,158,161,160,156,158,164,156,158,159,158,154,161,158,157,157,156,156,160,157,155,156,160,160,155,158,156,162,160,160,158,157,160,163,156,154,154,162,156,157,155,160,150,158,155,156,154,157,159,160,158,157,162,154,158,163,158,154,158,154,156,155,158,156,159,158,156,156,159,154,159,154,159,156,157,157,160,159,159,156,150,159,158,156,156,156,158,155,158,156,155,156,157,158,156,156,159,157,157,156,156,159,157,160,159,161,159,158,158,160,157,158,156,156,160,160,158,157,157,158,162,150,156,158,158,163,159,158,154,156,159,159,159,157,158,155,161,155,159,155,160,157,156,161,158,157,156,157,158,155,160,158,160,156,157,159,160,156,156,158,156,156,156,155,157,156,156,160,157,154,159,160,157,158,162,159,158,161,158,156,160,156,159,162,162,157,158,160,159,158,160,160,157,156,159,158,160,157,161,158,158,154,160,160,161,154,161,159,156,158,157,160,159,161,157,157,162,156,157,159,152,161,157,158,158,157,158,157,158,158,157,159,159,159,150,157,159,158,151,158,156,160,158,158,157,156,158,158,156,156,158,160,155,159,156,161,156,163,154,161,159,157,159,161,158,157,155,159,156,158,155,161,158,156,161,155,159,158,159,155,162,154,162,161,157,159,159,156,160,157,159,160,160,159,156,156,156,157,157,163,159,161,156,158,156,159,156,157,158,156,160,163,163,156,160,159,157,156,160,160,155,157,155,160,157,160,160,157,158,159,157,159,160,161,160,159,156,158,157,157,156,160,156,162,159,157,154,156,155,162,159,159,161,157,162,159,156,156,156,162,158,161,158,167,159,159,156,158,156,159,157,154,159,160,159,155,163,158,158,162,156,162,158,158,156,161,159,155,160,155,159,150,161,155,156,157,157,155,157,155,163,155,158,157,155,157,161,154,154,155,156,157,159,156,156,159,158,158,158,161,159,156,158,158,158,160,160,162,158,159,156,161,154,154,158,157,161,159,157,159,154,159,161,159,159,160,159,162,160,158,158,157,160,159,161,161,157,158,157,158,162,160,161,159,161,159,162,159,157,161,160,158,160,160,156,157,157,159,159,159,161,158,160,155,157,162,159,162,161,159,161,158,159,162,155,159,161,155,160,157,156,157,160,154,157,159,157,158,160,159,160,157,156,156,158,157,158,154,161,159,154,158,159,160,160,159,162,159,161,158,161,158,156,160,160,158,156,159,158,155,155,156,160,159,162,158,160,159,159,159,156,156,156,164,155,158,157,160,157,160,158,160,158,158,159,152,159,158,157,162,160,160,160,159,155,158,154,159,161,157,160,158,157,154,160,155,158,160,152,156,150,158,157,159,158,162,158,157,157,156,160,159,158,159,155,156,160,154,158,155,156,152,156,156,156,156,154,158,156,157,155,154,156,156,157,156,158,157,156,159,161,152,156,155,152,156,156,155,158,159,157,156,157,156,158,158,155,152,161,159,155,156,157,152,156,158,158,150,155,152,158,159,158,155,160,150,154,156,158,155,157,160,156,157,155,155,157,159,158,156,158,158,156,159,156,157,150,155,158,158,157,158,159,158,150,160,156,157,158,155,154,157,156,156,160,157,161,157,158,158,158,150,150,154,150,150,150,157,157,150,158,155,159,158,158,150,158,159,154,154,157,154,155,157,155,154,155,157,154,157,156,157,158,160,155,159,155,157,160,150,152,156,156,156,154,157,156,154,156,159,154,155,150,150,158,158,156,160,158,152,150,157,154,159,150,150,158,155,154,157,155,154,150,152,156,156,154,159,152,156,156,150,156,156,157,154,152,154,151,155,155,152,158,157,161,152,152,157,154,158,150,156,158,150,157,154,156,154,155,158,156,154,150,154,158,150,159,155,151,152,155,154,154,154,154,152,150,154,154,154,152,150,150,156,150,157,150,151,151,151,155,150,150,158,150,152,155,155,152,150,156,151,152,150,151,158,150,152,152,158,148,154,151,152,154,155,150,154,154,154,155,155,150,150,156,151,155,151,151,151,152,152,150,151,151,151,151,150,156,152,159,148,156,154,150,149,156,152,154,155,150,152,155,151,155,149,150,150,151,155,149,155,150,152,152,149,150,154,151,149,156,154,149,154,151,147,149,150,149,151,154,149,155,151,149,148,150,155,150,149,149,152,148,154,150,149,150,149,151,154,149,152,154,150,150,151,152,155,150,150,151,149,148,152,149}; int b[2048]={150,149,143,148,151,151,150,150,149,149,152,148,148,147,146,152,149,150,147,151,150,149,148,149,152,150,148,150,147,149,149,149,149,151,152,151,149,148,151,147,151,147,150,147,151,153,154,153,151,151,151,151,154,154,153,152,148,151,150,148,153,151,149,151,150,156,155,159,158,154,154,151,152,154,155,150,154,149,153,149,154,152,155,150,154,152,155,150,149,154,150,156,154,153,151,153,151,155,151,157,151,152,153,151,148,153,150,157,150,156,153,147,155,150,155,155,152,153,154,151,152,151,153,152,151,157,151,152,153,149,154,152,154,154,151,151,153,153,157,154,154,155,153,155,157,153,152,151,156,151,153,152,152,154,155,153,155,150,150,156,154,149,152,154,154,154,151,150,156,148,150,157,153,154,153,154,154,154,156,150,150,155,156,155,156,154,154,153,154,155,158,151,154,154,153,153,156,151,148,153,151,153,154,153,156,153,154,151,154,153,153,157,154,155,154,157,155,156,152,155,155,157,154,159,156,156,154,155,154,156,156,151,152,153,153,156,154,152,159,150,153,158,153,155,156,155,156,155,155,154,154,154,155,155,155,154,149,156,153,156,153,155,155,156,157,150,157,157,151,157,157,158,152,153,156,155,154,154,155,156,154,154,156,153,157,154,150,157,157,152,155,155,154,154,155,154,156,156,153,155,154,157,155,156,156,153,155,157,154,157,154,161,155,155,155,158,156,156,153,154,155,155,157,157,157,152,155,156,159,155,154,154,155,157,151,159,154,157,154,157,158,154,155,155,155,159,155,156,156,157,154,158,155,160,157,157,158,158,155,158,155,155,155,153,159,156,157,158,156,157,156,154,156,158,157,156,159,156,157,158,155,157,154,157,155,157,156,157,157,159,156,157,156,162,158,155,159,156,156,159,155,157,155,158,155,162,156,157,154,163,157,158,156,161,157,156,157,156,154,158,159,160,156,159,159,157,159,155,162,159,156,155,157,154,155,156,157,156,157,155,159,157,160,153,157,158,152,157,155,154,158,155,158,158,158,155,158,156,156,157,159,156,159,156,157,157,156,156,158,155,155,160,153,158,154,159,157,154,157,155,157,159,154,157,153,155,155,155,152,155,159,158,155,155,158,156,154,154,155,157,157,154,158,155,159,155,160,156,159,157,155,153,160,156,150,154,157,153,158,155,153,154,157,155,158,160,158,154,159,157,157,157,155,156,159,154,157,160,154,155,157,156,153,156,157,156,158,153,156,156,154,157,156,159,158,158,156,155,156,155,156,155,160,155,156,158,157,154,153,158,157,155,157,155,158,156,159,156,157,159,157,156,157,159,154,160,158,158,160,156,155,154,161,159,160,157,156,154,155,154,156,159,158,155,154,153,158,162,156,156,155,154,160,159,162,160,159,158,161,153,159,156,155,160,158,159,158,155,161,155,157,154,154,156,153,156,163,154,149,160,160,155,159,155,156,155,153,157,158,157,157,154,157,155,158,155,156,156,156,155,153,156,157,155,155,155,157,157,157,157,155,157,157,155,159,158,153,156,157,155,158,156,158,155,154,157,157,156,155,156,155,160,157,159,153,158,155,162,157,159,159,155,156,154,155,158,157,161,156,158,157,155,156,158,158,157,156,158,157,154,155,153,158,156,160,160,160,156,157,154,155,153,159,156,152,156,160,158,157,154,158,158,158,155,156,160,160,155,156,157,158,157,159,157,161,155,152,157,158,154,157,160,156,158,155,158,158,156,155,155,153,154,156,155,158,155,155,157,156,158,154,155,158,162,156,159,158,157,159,154,155,160,157,158,154,155,157,158,159,158,158,157,155,156,159,159,155,155,158,155,155,158,155,160,161,157,159,159,156,155,153,156,155,153,156,157,155,155,158,155,156,159,156,158,162,155,160,154,158,158,158,157,160,156,155,157,152,156,160,158,160,155,158,155,155,157,155,156,159,154,155,157,157,160,159,156,157,162,158,156,157,154,160,157,156,159,159,156,155,159,158,157,156,162,160,158,157,162,157,158,157,157,163,156,156,160,161,154,155,156,159,157,156,158,159,157,155,157,162,157,160,158,159,155,156,155,160,158,157,155,160,159,156,157,157,160,155,157,158,157,157,156,160,155,157,156,157,159,159,160,159,160,157,162,157,157,154,157,157,159,161,155,160,155,155,157,160,156,158,158,161,159,156,156,158,160,160,158,155,157,161,154,160,156,155,156,160,158,156,157,153,155,154,160,157,154,155,155,160,155,154,158,157,155,160,155,156,160,154,157,154,158,157,159,157,155,152,155,156,156,155,155,155,155,156,156,159,159,157,160,155,158,158,157,157,153,155,156,155,156,156,155,159,153,161,155,159,156,156,158,161,155,157,156,159,155,153,155,156,161,155,156,156,154,157,155,157,158,156,158,160,155,161,158,156,159,157,156,159,155,158,162,155,160,158,161,160,156,158,164,156,158,159,158,154,161,158,157,157,156,156,160,157,155,156,160,160,155,158,156,162,160,160,158,157,160,163,156,154,154,162,156,157,155,160,153,158,155,156,154,157,159,160,158,157,162,154,158,163,158,154,158,154,156,155,158,156,159,158,156,156,159,154,159,154,159,156,157,157,160,159,159,156,153,159,158,156,156,156,158,155,158,156,155,156,157,158,156,156,159,157,157,156,156,159,157,160,159,161,159,158,158,160,157,158,156,156,160,160,158,157,157,158,162,153,156,158,158,163,159,158,154,156,159,159,159,157,158,155,161,155,159,155,160,157,156,161,158,157,156,157,158,155,160,158,160,156,157,159,160,156,156,158,156,156,156,155,157,156,156,160,157,154,159,160,157,158,162,159,158,161,158,156,160,156,159,162,162,157,158,160,159,158,160,160,157,156,159,158,160,157,161,158,158,154,160,160,161,154,161,159,156,158,157,160,159,161,157,157,162,156,157,159,152,161,157,158,158,157,158,157,158,158,157,159,159,159,153,157,159,158,151,158,156,160,158,158,157,156,158,158,156,156,158,160,155,159,156,161,156,163,154,161,159,157,159,161,158,157,155,159,156,158,155,161,158,156,161,155,159,158,159,155,162,154,162,161,157,159,159,156,160,157,159,160,160,159,156,156,156,157,157,163,159,161,156,158,156,159,156,157,158,156,160,163,163,156,160,159,157,156,160,160,155,157,155,160,157,160,160,157,158,159,157,159,160,161,160,159,156,158,157,157,156,160,156,162,159,157,154,156,155,162,159,159,161,157,162,159,156,156,156,162,158,161,158,167,159,159,156,158,156,159,157,154,159,160,159,155,163,158,158,162,156,162,158,158,156,161,159,155,160,155,159,153,161,155,156,157,157,155,157,155,163,155,158,157,155,157,161,154,154,155,156,157,159,156,156,159,158,158,158,161,159,156,158,158,158,160,160,162,158,159,156,161,154,154,158,157,161,159,157,159,154,159,161,159,159,160,159,162,160,158,158,157,160,159,161,161,157,158,157,158,162,160,161,159,161,159,162,159,157,161,160,158,160,160,156,157,157,159,159,159,161,158,160,155,157,162,159,162,161,159,161,158,159,162,155,159,161,155,160,157,156,157,160,154,157,159,157,158,160,159,160,157,156,156,158,157,158,154,161,159,154,158,159,160,160,159,162,159,161,158,161,158,156,160,160,158,156,159,158,155,155,156,160,159,162,158,160,159,159,159,156,156,156,164,155,158,157,160,157,160,158,160,158,158,159,152,159,158,157,162,160,160,160,159,155,158,154,159,161,157,160,158,157,154,160,155,158,160,152,156,153,158,157,159,158,162,158,157,157,156,160,159,158,159,155,156,160,154,158,155,156,152,156,156,156,156,154,158,156,157,155,154,156,156,157,156,158,157,156,159,161,152,156,155,152,156,156,155,158,159,157,156,157,156,158,158,155,152,161,159,155,156,157,152,156,158,158,150,155,152,158,159,158,155,160,150,154,156,158,155,157,160,156,157,155,155,157,159,158,156,158,158,156,159,156,157,153,155,158,158,157,158,159,158,153,160,156,157,158,155,154,157,156,156,160,157,161,157,158,158,158,153,153,154,153,153,153,157,157,150,158,155,159,158,158,153,158,159,154,154,157,154,155,157,155,154,155,157,154,157,156,157,158,160,155,159,155,157,160,153,152,156,156,156,154,157,156,154,156,159,154,155,153,153,158,158,156,160,158,152,153,157,154,159,153,153,158,155,154,157,155,154,153,152,156,156,154,159,152,156,156,153,156,156,157,154,152,154,151,155,155,152,158,157,161,152,152,157,154,158,153,156,158,153,157,154,156,154,155,158,156,154,153,154,158,153,159,155,151,152,155,154,154,154,154,152,153,154,154,154,152,153,153,156,153,157,153,151,151,151,155,153,153,158,153,152,155,155,152,153,156,151,152,153,151,158,153,152,152,158,148,154,151,152,154,155,153,154,154,154,155,155,153,153,156,151,155,151,151,151,152,152,150,151,151,151,151,150,156,152,159,148,156,154,150,149,156,152,154,155,153,152,155,151,155,149,153,150,151,155,149,155,153,152,152,149,153,154,151,149,156,154,149,154,151,147,149,153,149,151,154,149,155,151,149,148,150,155,150,149,149,152,148,154,153,149,150,149,151,154,149,152,154,153,150,151,152,155,153,150,151,149,148,152,149 }; DataSource::DataSource(QObject *parent) : QObject(parent), m_index(-1) { generateData(0, 0, 0); } void DataSource::update(QAbstractSeries *series, int seriesIndex) { if (series) { QXYSeries *xySeries = static_cast<QXYSeries *>(series); const QVector<QVector<QPointF> > &seriesData = m_data.at(seriesIndex); if (seriesIndex == 0) m_index++; if (m_index > seriesData.count() - 1) m_index = 0; QVector<QPointF> points = seriesData.at(m_index); // Use replace instead of clear + append, it's optimized for performance xySeries->replace(points); } } void DataSource::handleSceneChanged() { m_dataUpdater.start(); } void DataSource::updateAllSeries() { static int frameCount = 0; static QString labelText = QStringLiteral("FPS: %1"); for (int i = 0; i < m_seriesList.size(); i++) update(m_seriesList[i], i); frameCount++; int elapsed = m_fpsTimer.elapsed(); if (elapsed >= 1000) { elapsed = m_fpsTimer.restart(); qreal fps = qreal(0.1 * int(10000.0 * (qreal(frameCount) / qreal(elapsed)))); m_fpsLabel->setText(labelText.arg(QString::number(fps, 'f', 1))); m_fpsLabel->adjustSize(); frameCount = 0; } m_data.clear(); // Append the new data depending on the type QVector<QVector<QPointF> > seriesData; QVector<QPointF> points; // points.reserve(2048); for (int j(0); j < 2048; j++) { qreal x(0); qreal y(0); if(shift==0) { y = b[j] ; x=j; }else { y = c[j] ; x=j; } points.append(QPointF(x, y)); } seriesData.append(points); m_data.append(seriesData); if(shift==0) { shift=1; }else { shift=0; } } void DataSource::startUpdates(const QList<QXYSeries *> &seriesList, QLabel *fpsLabel) { m_seriesList = seriesList; m_fpsLabel = fpsLabel; m_dataUpdater.setInterval(500); m_dataUpdater.setSingleShot(true); QObject::connect(&m_dataUpdater, &QTimer::timeout,this, &DataSource::updateAllSeries); m_fpsTimer.start(); updateAllSeries(); } void DataSource::generateData(int seriesCount, int rowCount, int colCount) { // Remove previous data foreach (QVector<QVector<QPointF> > seriesData, m_data) { foreach (QVector<QPointF> row, seriesData) row.clear(); } m_data.clear(); // Append the new data depending on the type for (int k(0); k < seriesCount; k++) { QVector<QVector<QPointF> > seriesData; for (int i(0); i < rowCount; i++) { QVector<QPointF> points; points.reserve(colCount); for (int j(0); j < colCount; j++) { qreal x(0); qreal y(0); if(shift==0) { y = a[j] ; x=j; }else { y = b[j] ; x=j; } points.append(QPointF(x, y)); } seriesData.append(points); } m_data.append(seriesData); } if(shift==0) { shift=1; }else { shift=0; } qDebug()<<"test"; } //***********main.cpp**********// #include "datasource.h" #include <QtWidgets/QApplication> #include <QtWidgets/QMainWindow> #include <QtCharts/QChartView> #include <QtCharts/QLineSeries> #include <QtCharts/QScatterSeries> #include <QtCharts/QValueAxis> #include <QtCharts/QLogValueAxis> #include <QtWidgets/QLabel> QT_CHARTS_USE_NAMESPACE int main(int argc, char *argv[]) { QApplication a(argc, argv); QStringList colors; colors << "red" << "blue" << "green" << "black"; QChart *chart = new QChart(); chart->legend()->hide(); QValueAxis *axisX = new QValueAxis; QValueAxis *axisY = new QValueAxis; chart->addAxis(axisX, Qt::AlignBottom); chart->addAxis(axisY, Qt::AlignLeft); const int seriesCount = 1; const int pointCount = 2048; chart->setTitle("OpenGL Accelerated Series"); QList<QXYSeries *> seriesList; for (int i = 0; i < seriesCount; i++) { QXYSeries *series = 0; int colorIndex = i % colors.size(); if (i % 2) { series = new QScatterSeries; QScatterSeries *scatter = static_cast<QScatterSeries *>(series); scatter->setColor(QColor(colors.at(colorIndex))); scatter->setMarkerSize(qreal(colorIndex + 2) / 2.0); // Scatter pen doesn't have affect in OpenGL drawing, but if you disable OpenGL drawing // this makes the marker border visible and gives comparable marker size to OpenGL // scatter points. scatter->setPen(QPen("black")); } else { series = new QLineSeries; series->setPen(QPen(QBrush(QColor(colors.at(colorIndex))), qreal(colorIndex + 2) / 2.0)); } seriesList.append(series); //![1] series->setUseOpenGL(true); //![1] chart->addSeries(series); series->attachAxis(axisX); series->attachAxis(axisY); } if (axisX->type() == QAbstractAxis::AxisTypeLogValue) axisX->setRange(0.1, 2048.0); else axisX->setRange(0, 2048.0); if (axisY->type() == QAbstractAxis::AxisTypeLogValue) axisY->setRange(0.1, 255.0); else axisY->setRange(0, 255.0); QChartView *chartView = new QChartView(chart); QMainWindow window; window.setCentralWidget(chartView); window.resize(600, 400); window.show(); DataSource dataSource; dataSource.generateData(seriesCount, 1, pointCount); QLabel *fpsLabel = new QLabel(&window); QLabel *countLabel = new QLabel(&window); QString countText = QStringLiteral("Total point count: %1"); countLabel->setText(countText.arg(pointCount * seriesCount)); countLabel->adjustSize(); fpsLabel->move(10, 2); fpsLabel->adjustSize(); fpsLabel->raise(); fpsLabel->show(); countLabel->move(10, fpsLabel->height()); fpsLabel->raise(); countLabel->show(); // We can get more than one changed event per frame, so do async update. // This also allows the application to be responsive. QObject::connect(chart->scene(), &QGraphicsScene::changed, &dataSource, &DataSource::handleSceneChanged); dataSource.startUpdates(seriesList, fpsLabel); return a.exec(); }
Qt5 C++ Application Crashes for unknown reasons [closed]
Closed. This question needs debugging details. It is not currently accepting answers. Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question. Closed 5 years ago. Improve this question I am really struggling with that strange bug for some time. My application crashes even before widgets are shown (but window itself is shown). Here is my code: main.cpp #include "mainwindow.h" #include <QApplication> #include <QTimer> int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.setWindowTitle("Snake"); w.resize(500, 500); w.show(); QTimer* timer = new QTimer(); while(!w.checkCollision()) { if(timer -> isActive() == false) { w.play(); timer -> start(1); } } return a.exec(); } mainwindow.h #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QPainter> #include <QKeyEvent> #include <QDebug> #include <snakeclass.h> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); Snake snake; void paintEvent(QPaintEvent*); void keyEvent(QKeyEvent* keyevent); void move(); bool checkCollision(); void play(); ~MainWindow(); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H mainwindow.cpp #include "mainwindow.h" #include "ui_mainwindow.h" #include <QPainter> #include <QPainterPath> #include <QKeyEvent> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { } void MainWindow::paintEvent(QPaintEvent*) { QPainter painter(this); // Draw black background. painter.drawRect(0, 0, 500, 500); painter.fillRect(0, 0, 500, 500, Qt::black); for(unsigned int i = 0; i < snake.getLength(); i++) { // Draw green snake's body. painter.setPen(Qt::green); painter.setBrush(Qt::green); // If i = 0, so if we are drawing snake's head. if(i == 0) { // Draw red head. painter.setPen(Qt::red); painter.setBrush(Qt::red); } painter.drawEllipse((snake.getDot(i)).x, (snake.getDot(i)).y, 10, 10); } } void MainWindow::keyEvent(QKeyEvent* keyevent) { if(keyevent -> key() == Qt::Key_Left) { if(snake.getDirection() != Snake::Direction::RIGHT) { snake.setDirection(Snake::Direction::LEFT); } } else if(keyevent -> key() == Qt::Key_Right) { if(snake.getDirection() != Snake::Direction::LEFT) { snake.setDirection(Snake::Direction::RIGHT); } } else if(keyevent -> key() == Qt::Key_Up) { if(snake.getDirection() != Snake::Direction::DOWN) { snake.setDirection(Snake::Direction::UP); } } else if(keyevent -> key() == Qt::Key_Down) { if(snake.getDirection() != Snake::Direction::UP) { snake.setDirection(Snake::Direction::DOWN); } } } void MainWindow::move() { for(unsigned int i = snake.getLength(); i > 0; i--) { snake.editDot((snake.getDot(i - 1)).x, (snake.getDot(i - 1)).y, i, (snake.getDot(i - 1)).direction); } if(snake.getDirection() == Snake::Direction::UP) { if(int(snake.getDot(0).y - 10) < 0) { snake.editDot((snake.getDot(0)).x, 500, 0, snake.getDirection()); } else { snake.editDot((snake.getDot(0)).x, (snake.getDot(0)).y - 10, 0, snake.getDirection()); } } else if(snake.getDirection() == Snake::Direction::DOWN) { if(((snake.getDot(0)).y + 10) > 490) { snake.editDot((snake.getDot(0)).x, 0, 0, snake.getDirection()); } else { snake.editDot((snake.getDot(0)).x, (snake.getDot(0)).y + 10, 0, snake.getDirection()); } } else if(snake.getDirection() == Snake::Direction::RIGHT) { if(((snake.getDot(0)).x + 10) > 490) { snake.editDot(0, (snake.getDot(0)).y, 0, snake.getDirection()); } else { snake.editDot((snake.getDot(0)).x + 10, (snake.getDot(0)).y, 0, snake.getDirection()); } } else if(snake.getDirection() == Snake::Direction::LEFT) { if((int((snake.getDot(0)).x) - 10) < 0) { snake.editDot(500, (snake.getDot(0)).y, 0, snake.getDirection()); } else { snake.editDot((snake.getDot(0)).x - 10, (snake.getDot(0)).y, 0, snake.getDirection()); } } } bool MainWindow::checkCollision() { for(unsigned int i = 0; i < snake.getLength(); i++) { for(unsigned int j = 0; j < snake.getLength(); j++) { if((i != j) && ((snake.getDot(i)).x == (snake.getDot(j)).x) && ((snake.getDot(i)).y == (snake.getDot(j)).y)) { return true; } } } return false; } void MainWindow::play() { //move(); update(); } MainWindow::~MainWindow() { delete ui; } snakeclass.h #ifndef SNAKECLASS #define SNAKECLASS #include <vector> class Snake { public: enum class Direction { LEFT, RIGHT, UP, DOWN }; // Dot is a part of the snake. struct dot { unsigned int x; unsigned int y; // Number of the dot (head is 0). unsigned int dotNumber; // Direction of the particular dot. Direction direction; }; unsigned int getLength(); unsigned int getScore(); unsigned int getSpeed(); Direction getDirection(); dot getDot(unsigned int dotNumber); void setLength(unsigned int length); void setScore(unsigned int score); void setSpeed(unsigned int speed); void setDirection(Direction direction); // Returns new dot's dotNumber. unsigned int newDot(); void editDot(unsigned int x, unsigned int y, unsigned int dotNumber, Direction direction); private: unsigned int length = 3; unsigned int score = 0; unsigned int speed = 1; Direction direction = Direction::RIGHT; std::vector <dot> dots = {dot {250, 250, 0, Direction::RIGHT}, dot {240, 250, 1, Direction::RIGHT}, dot {230, 250, 2, Direction::RIGHT}}; }; #endif // SNAKECLASS snakeclass.cpp #include "snakeclass.h" unsigned int Snake::getLength() { return length; } unsigned int Snake::getScore() { return score; } unsigned int Snake::getSpeed() { return speed; } Snake::Direction Snake::getDirection() { return direction; } Snake::dot Snake::getDot(unsigned int dotNumber) { return dots.at(dotNumber); } void Snake::setLength(unsigned int length) { this -> length = length; } void Snake::setScore(unsigned int score) { this -> score = score; } void Snake::setSpeed(unsigned int speed) { this -> speed = speed; } void Snake::setDirection(Snake::Direction direction) { this -> direction = direction; } unsigned int Snake::newDot() { dot newDot; newDot.dotNumber = dots.size(); dots.push_back(newDot); length ++; return newDot.dotNumber; } void Snake::editDot(unsigned int x, unsigned int y, unsigned int dotNumber, Snake::Direction direction) { for(unsigned int i = 0; i < dots.size(); i++) { if((dots.at(i)).dotNumber == dotNumber) { dots.at(i).x = x; dots.at(i).y = y; dots.at(i).direction = direction; } } } I am new to Qt5 and this is my first project involving painter and keyboard events. Could you help me to figure out what the problem in the code above is? Thank you for all the answers!
My application crashes even before widgets are shown (but window itself is shown). It doesn't crash. In main.cpp there is an infinite loop in which some results are expected, namely !w.checkCollision(), but since there is no event loop running in main.cpp nothing happens and the programs hangs there waiting in vain. As an answer to your question, in order to see the widgets add QApplication::processEvents(); in the following way: while(!w.checkCollision()) { QApplication::processEvents(); if(timer -> isActive() == false) { w.play(); timer -> start(1); } } However, with this approach you will face further problems. So I would strongly advise you to take a look at the examples in the Qt Creator in order to see which is the correct way of using the library as thought by the Qt developers.
Qt - adding elements to map and memory leaks
I am working on a matrix calculator and I encountered a really annoying problem, have been trying to fix it for 3 hours now, but it's getting worse instead of getting better. Maybe you will be able to help. This is my MainWindow class: #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QPushButton> #include <QGridLayout> #include <QLabel> #include "addmatrix.h" #include "memory.h" #include "matrixcreation.h" #include <QMap> #include "matrix.h" namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(MainWindow *parent = 0); ~MainWindow(); private slots: void on_createButton_clicked(); void setMatrix(Matrix *matrix); private: Matrix getMatrixFromMemory(QString &name); void addMatrixToMemory(); Ui::MainWindow *ui; AddMatrix *add; MatrixCreation *matrixCreate; QMap <QString, Matrix> matrixMap; }; #endif // MAINWINDOW_H .cpp file #include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(MainWindow *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); this->setWindowTitle("Matrix Calculator"); add = NULL; matrixCreate = NULL; } MainWindow::~MainWindow() { delete ui; delete add; delete matrixCreate; matrixMap.clear(); } void MainWindow::on_createButton_clicked() { if (add != NULL) { delete add; add = new AddMatrix; } else add = new AddMatrix; if (matrixCreate != NULL) { ui->label->setText(getMatrixFromMemory(matrixCreate->getMatrix()->getName()).getName()); delete matrixCreate; matrixCreate = new MatrixCreation; } else matrixCreate = new MatrixCreation; // Polaczenie sygnalow ze slotami // Sluzy ustawieniu liczby wierszy w matrixCreate connect(add->getCombo1(), SIGNAL(currentIndexChanged(QString)), matrixCreate, SLOT(setRows(QString))); // Jak wyzej, tylko kolumn connect(add->getCombo2(), SIGNAL(currentIndexChanged(QString)), matrixCreate, SLOT(setColumns(QString))); // Ustawienie pola name w matrixCreate connect(add->getEdit(), SIGNAL(textChanged(QString)), matrixCreate, SLOT(setName(QString))); // Po ustawieniu liczby wierszy i kolumn oraz nazwy macierzy - wywola sie slot updateTable // ktory sluzy do ustawienia rozmiaru okna i tabeli connect(add, SIGNAL(setupSuccessful()), matrixCreate, SLOT(updateTable())); // Po ustawieniu wierszy, kolumn, ustawieniu nazwy, rozmiarow, wywola sie slot show matrixCreate connect(add, SIGNAL(setupSuccessful()), matrixCreate, SLOT(show())); // Sluzy dodaniu macierzy do pamieci (mapy) connect(matrixCreate, SIGNAL(matrixReady(Matrix*)), this, SLOT(setMatrix(Matrix*))); add->show(); } void MainWindow::setMatrix(Matrix *matrix) { matrixMap[matrix->getName()] = *matrix; } Matrix MainWindow::getMatrixFromMemory(QString &name) { return matrixMap[name]; } As you can see I have a QMap in my MainWindow. I also have a an instance of MatrixCreation class called matrixCreate. Here is MatrixCreation class: #ifndef MATRIXCREATION_H #define MATRIXCREATION_H #include <QDialog> #include <QTableView> #include <QPushButton> #include <QStandardItem> #include <QTableWidget> #include <QMainWindow> #include "matrix.h" #include "memory.h" #include "addmatrix.h" #include <windows.h> namespace Ui { class MatrixCreation; } class MatrixCreation : public QWidget { Q_OBJECT public: explicit MatrixCreation(QWidget *parent = 0); ~MatrixCreation(); QTableWidget *getTable(); Matrix *getMatrix(); private slots: void on_okButton_clicked(); void updateTable(); void setRows(QString rows); void setColumns(QString columns); void setName(QString name); signals: void matrixReady(Matrix *matrix); private: Ui::MatrixCreation *ui; int rows; int columns; int **matrix; QString name; Matrix *newMatrix; }; #endif // MATRIXCREATION_H .cpp file #include "matrixcreation.h" #include "ui_matrixcreation.h" MatrixCreation::MatrixCreation(QWidget *parent) : QWidget(parent), ui(new Ui::MatrixCreation) { ui->setupUi(this); this->resize(150, 50); // Ustawienie rozmiaru wysokosci wiersza na 40 piksele ui->tableWidget->verticalHeader()->setDefaultSectionSize(40); // Ustawienie rozmiaru szerokosci kolumny na 94 piksele ui->tableWidget->horizontalHeader()->setDefaultSectionSize(94); // Dopasowanie rozmiaru kolumn do rozmiaru tabeli ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); ui->tableWidget->verticalHeader()->setSectionResizeMode(QHeaderView::Stretch); // Wylaczenie scrollbarow tabeli ui->tableWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); ui->tableWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); rows = 1; columns = 1; matrix = NULL; newMatrix = new Matrix; } MatrixCreation::~MatrixCreation() { delete ui; if (matrix != NULL) { for (int i = 0; i < rows; i++) delete matrix[i]; } delete newMatrix; } void MatrixCreation::setRows(QString rows) { this->rows = rows.toInt(); } void MatrixCreation::setColumns(QString columns) { this->columns = columns.toInt(); } // Metoda odpowiedzialna za utworzenie odpowiedniej ilosci wierszy i kolumn // oraz ustawienie odpowiedniej wielkosci okna i rozmiaru tabeli void MatrixCreation::updateTable() { // stale roznice miedzy szerokoscia i wysokoscia okna i tabeli int w = 323 - 305; int h = 300 - 227 + 15; for(int i = 0; i < rows; i++) { ui->tableWidget->insertRow(i); h += 35; } for(int j = 0; j < columns; j++) { ui->tableWidget->insertColumn(j); w += 50; } this->resize(w, h); this->setMinimumSize(w, h); ui->retranslateUi(this); this->setWindowTitle("Matrix Creation"); } QTableWidget *MatrixCreation::getTable() { return ui->tableWidget; } void MatrixCreation::on_okButton_clicked() { matrix = new int *[rows]; for(int j = 0; j < rows; j++) { matrix[j] = new int[columns]; } for(int i = 0; i<rows; i++) { for(int j = 0; j<columns; j++) { matrix[i][j] = ui->tableWidget->item(i, j)->text().toInt(); } } // Ustawienie pol skladowych w zmiennej newMatrix klasy Matrix newMatrix->setColumns(columns); newMatrix->setRows(rows); newMatrix->setName(name); newMatrix->setMatrix(matrix); emit matrixReady(newMatrix); this->close(); } void MatrixCreation::setName(QString name) { this->name = name; } Matrix *MatrixCreation::getMatrix() { return newMatrix; } What is the problem: I want to add a created matrix to a QMap by emiting this signal: emit matrixReady(newMatrix); a Matrix class is used to hold all the elements of matrix (rows, cols, values of cells and name). However, Matrix objects are not being added to QMap. But, when I delete this line in MatrixCreation destructor: delete newMatrix; It works. Second problem: When I am closing my application and MainWindow destructor gets called, while destroying a map it shows an error : BLOC_TYPE_IS_VALID bla bla... I don't know how to fix it, however I will keep on trying. Any help will be appreciated.
void MainWindow::setMatrix(Matrix *matrix) { matrixMap[matrix->getName()] = *matrix; } You're adding copy of the matrix to your map. So here you have a leak. void MainWindow::setMatrix(Matrix *matrix) { matrixMap[matrix->getName()] = *matrix; delete matrix; } This should fix your problem. Use valgrind to profile your application and find memory leaks: http://valgrind.org/docs/manual/quick-start.html
Qt Creator Platformer Game - Can't make it work (Beginner with QGraphics)
i'm making a little game just for pratice. I basically want to make my character (a red triangle) move left and right, jump, etc. The program is still very small at this state, And I wanna know 'how' I should do such things. I've created a Player Class(QObject, QGraphicsPolygonItem) and a Game Class(QGraphicsView). It worked at first when I gave the Player Class a method for KeyPressEvent, but I had a problem with the jump loop : I wanted to do a scene->update() inside my jump loop, But I couldn't because the scene is an attribute of my Game Class. Then, I tried giving the Game Class the PressKeyEvent method, so it would move the Player * player attribute. So basically, what I want is to be able to see the position of my rect update every iteration of my for loop. Can I do that ? Hope this makes sense, and as always, thanks a lot guys !! Player.h & Player.cpp #pragma once #include <QGraphicsPolygonItem> #include <QBrush> class Player : public QObject, public QGraphicsPolygonItem { Q_OBJECT public: Player(); // Setters void setIsJumping(bool); // Getters bool getIsJumping(); public slots: private: bool isJumping; }; #include "Player.h" Player::Player() { // *************** // Draw the player // *************** QVector<QPointF> gemPoints; gemPoints << QPointF(0, 2) << QPointF(1, 0) << QPointF(2, 2); // Size int SCALE_BY = 8; for (size_t i = 0; i < gemPoints.size(); i++) { gemPoints[i] *= SCALE_BY; } // Create the polygon QPolygonF gemModel(gemPoints); setPolygon(gemModel); setPos(400, 500); // Color QBrush brush; brush.setStyle(Qt::SolidPattern); brush.setColor(Qt::red); setBrush(brush); // Make player focusable this->setFlag(QGraphicsItem::ItemIsFocusable); this->setFocus(); } void Player::setIsJumping(bool jump) { if (jump == true) { isJumping = true; } else { isJumping = false; } } bool Player::getIsJumping() { return isJumping; } Game.h & Game.cpp #pragma once #include <QGraphicsView> #include <QGraphicsScene> #include <QKeyEvent> #include "Player.h" class Game : public QGraphicsView { Q_OBJECT public: // Constructors Game(QWidget* parent = NULL); // Methods void start(); void jump(); void keyPressEvent(QKeyEvent *event); // Attributes QGraphicsScene* scene; Player* player; }; #include "Game.h" Game::Game(QWidget* parent) { // Set up the screen setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setFixedSize(1024, 768); // Set up the scene scene = new QGraphicsScene(); scene->setSceneRect(0, 0, 1024, 768); setScene(scene); } void Game::start() { scene->clear(); player = new Player(); scene->addItem(player); } void Game::keyPressEvent(QKeyEvent * event) { if (event->key() == Qt::Key_Left) { player->setPos(x() - 3, y()); } else if (event->key() == Qt::Key_Right) { player->setPos(x() + 3, y()); } else if (event->key() == Qt::Key_Space) { for (size_t i = 0; i < 10; i++) { player->setIsJumping(true); this->jump(); } } } void Game::jump() { if (player->getIsJumping() == true) { for (size_t i = 0; i < 100; i++) { this->player->setPos(x(), y() - 0.1); this->update(); } player->setIsJumping(false); } } Main.cpp #include "plateforme.h" #include <QtWidgets/QApplication> #include "Game.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); Game game; game.show(); game.start(); return a.exec(); } The problem is that I can't move the player correctly now, It moves only once and in a weird way. Any help is appreciated.
The problem is that when you set the position for player, you should modify the coordinates of player and not of this. Therefore, whenever you want to move the player, use: player->setPos(player->x() - 3, player->y()); ^ ^ and the same for jumping in your loop: player->setPos(player->x(), player->y() - 0.1); ^ ^ When you use setPos(x()-3, y()), it sets the player position to position of your QGraphicsView, that is why it disappears from the view. Good luck with your game!
QGraphicsView doesn't always update
Hi I've got a GridLayout which has 64 GraphicsViews on it (I know it's alot but it's the only way i could think of doing this at this point in time). Now i'm currently just drawing a random line on each of these graphics views on a timer tick. This works but only for the 8 of the Graphics, Create Graphics Views void Simulation::createGraphicsViews(){ for(int i = 0; i < 64; i++){ for(int j = 0; j < 8; j++){ graphicsScene[i] = new QGraphicsScene(); graphicsView[i] = new QGraphicsView(graphicsScene[i]); simui->gridLayout->addWidget(graphicsView[i], i/8, j); } } } Random Line in each graphics view for(int x = 0; x < 64; x++){ x1 = qrand()%(50+1) - 1; y1 = qrand()%(50+1)-1; x2 = qrand()%(50+1)-1; y2 = qrand()%(50+1)-1; graphicsScene[x]->addLine(x1,y1,x2,y2); qDebug() << "adding line to" << x << "at" << x1 <<","<<y1<<","<<x2<<","<<y2; } show updated graphics view for(int x = 0; x < 64; x++){ graphicsView[x]->show(); qDebug()<<"showing" << x; } I've looked through it for the last 2 hours trying multiple approaches none of which have fixed this problem, I'm assuming it's probably something stupid but I just can't figure it out Any help is greatly appreciated Thank you Also if i try to update any of the Graphics Views other than the ones which work they still don't update. https://gist.github.com/gazza126/f43d5b0377649782a35d -- Full Code (that does anything)
The below works. Make sure that you enable C++11 in your .pro file: add CONFIG += c++11 to the project file. #include <QApplication> #include <QGraphicsScene> #include <QGraphicsView> #include <QGraphicsLineItem> #include <QGridLayout> #include <QTime> #include <QTimer> #include <array> class View : public QGraphicsView { public: View(QWidget *parent = 0) : QGraphicsView(parent) { setRenderHint(QPainter::Antialiasing); } void resizeEvent(QResizeEvent *) { fitInView(-1, -1, 2, 2, Qt::KeepAspectRatio); } }; template <typename Container> void updateScenes(Container & views) { auto angle = 360.0/1000.0 * (QTime::currentTime().msecsSinceStartOfDay() % 1000); for (auto & view : views) { auto scene = view.scene(); scene->clear(); auto * line = scene->addLine(-1, 0, 1, 0, QPen(Qt::darkBlue, 0.1)); line->setRotation(angle); } } int main(int argc, char *argv[]) { QApplication a(argc, argv); QGraphicsScene s; QTimer timer; QWidget window; QGridLayout layout(&window); std::array<View, 64> views; int i = 0; for (auto & view : views) { view.setScene(new QGraphicsScene(&view)); layout.addWidget(&view, i/8, i%8); ++ i; } QObject::connect(&timer, &QTimer::timeout, [&views]{ updateScenes(views); }); timer.start(50); window.show(); return a.exec(); }