I have a simple QDialog
that shows a QLabel
in black text. I'd like for the QLabel
's text to turn red when I press the a
key. I am using the designer to make the dialog. Here is my code:
myDialog.h
#include <QDialog>
#include <QWidget>
namespace Ui {
class myDialog;
}
class myDialog : public QDialog
{
Q_OBJECT
public:
explicit myDialog(QWidget* parent = 0);
~myDialog();
private:
Ui::myDialog* ui;
protected:
void keyPressEvent(QKeyEvent* event);
};
myDialog.cpp
#include "myDialog.h"
#include "ui_myDialog.h"
#include <QKeyEvent>
myDialog::myDialog(QWidget* parent) :
QDialog(parent),
ui(new Ui::myDialog)
{
ui->setupUi(this);
}
void myDialog::eventPressEvent(QKeyEvent* event)
{
if (event->key()==Qt::Key_A){
Ui_myDialog::label1->setStyleSheet(QStringLiteral("QLabel{color: rgb(170, 0, 0);}"));
} else {
qDebug << "FAIL";
}
}
myDialog::~myDialog()
{
delete ui;
}
ui_mydialog.h
/********************************************************************************
** Form generated from reading UI file 'about.ui'
** Created by: Qt User Interface Compiler version 5.5.0
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_MYDIALOG_H
#define UI_MYDIALOG_H
...<snip>...
QT_BEGIN_NAMESPACE
class Ui_myDialog
{
public:
QLabel *label1;
void setupUi(QDialog *myDialog)
{
...<snip>...
label1 = new QLabel(myDialog);
label1->setObjectName(QStringLiteral("label1"));
label1->setGeometry(QRect(50, 333, 16, 20));
label1->setFont(font);
label1->setAlignment(Qt::AlignCenter);
...<snip>...
} // setupUi
...<snip>...
namespace Ui {
class myDialog: public Ui_myDialog {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_MYDIALOG_H
So, here's the issue. When I build the project, a file called ui_mydialog.h
gets created and is generated in the build folder. This file even says it was auto-generated by the Qt User Interface Compiler. When I try to change the stylesheet of label1
(which is declared in ui_mydialog.h
) in myDialog.cpp
using the line:
Ui_myDialog::label1->setStyleSheet(QStringLiteral("QLabel{color: rgb(170, 0, 0);}"));
...I get an error that says error: invalid use of non-static data member 'Ui_myDialog::label1'
. This is where I'm stuck. How would I go about correctly passing label1
into the void myDialog::eventPressEvent(QKeyEvent* event)
member function and modifying it?
Any help would be appreciated.