lundi 13 juillet 2020

Proper way to pass QColor object into Qdialog subclass

I am having a problem with a QDialog subclass that I am using to pass two QT Objects into: QColor and QFont. If I pass by reference the application unexpectedly crashes before it can run even though it compiled out without error.

I was able to get it to work using pointers but it looks ugly, and messes up the rest of the code. I want to get it working by reference and refrain from using 'New' keyword to instantiate QFont or QColor classes. So basically my working subclass constructer using pointers looks like this:

HEADER:

class MySettingsDialog : public QDialog
{
Q_OBJECT

public:
explicit MySettingsDialog(QColor *acolor, QFont *afont, QWidget *parent=0);

CLASS FILE: MySettingsDialog::MySettingsDialog(QColor *acolor, QFont *afont, QWidget *parent) : QDialog(parent, Qt::WindowCloseButtonHint), m_color(*acolor), m_font(*afont), ui(new Ui::MySettingsDialog) {

ui->setupUi(this);
}

This way works but I have to in my MainWindow.cpp file declare for example:

QFont * systemFont;

 systemFont = New QFont("myfont whatever");

And everywhere I want to apply that font I have to unmask like this: ui->mylabel->setfont(*systemFont).

Before I wasn't using 'new' to instantiate my systemFont variable and systemFont wasn't declared as a pointer in the header file. Such that if Mydialog was declared like this the program crashes:

DOESNT WORK:

HEADER

 explicit MySettingsDialog(QColor &acolor, QFont &afont, QWidget *parent=0);

CLASS FILE:
 MySettingsDialog::MySettingsDialog(QColor &acolor, QFont &afont, QWidget      *parent) :
 QDialog(parent, Qt::WindowCloseButtonHint), m_color(acolor), m_font(afont),
 ui(new Ui::MySettingsDialog)
{

ui->setupUi(this);
 }

Mainwindow:

MySettingsDialog(systemColor, systemFont, this);

What am I doing wrong?

Thanks

Aucun commentaire:

Enregistrer un commentaire