[英]Changing color of QLabel text? Accessing and modifying members of .ui file? [Qt]
我有一个简单的QDialog
,它以黑色文本显示QLabel
。 我希望QLabel
的文本在按a
键时变为红色。 我正在使用设计器进行对话框。 这是我的代码:
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
所以,这就是问题。 当我构建项目时,将创建一个名为ui_mydialog.h
的文件,并在构建文件夹中生成该文件。 该文件甚至说它是由Qt用户界面编译器自动生成的。 当我尝试使用以下行在myDialog.cpp
更改label1
的样式表(在ui_mydialog.h
中声明)时:
Ui_myDialog::label1->setStyleSheet(QStringLiteral("QLabel{color: rgb(170, 0, 0);}"));
...我得到一个错误,指出error: invalid use of non-static data member 'Ui_myDialog::label1'
。 这就是我卡住的地方。 我该如何正确地将label1
传递给void myDialog::eventPressEvent(QKeyEvent* event)
成员函数并对其进行修改?
任何帮助,将不胜感激。
在非静态成员上使用Ui_myDialog::
是不正确的。
您需要更换
Ui_myDialog::label1->setStyleSheet(QStringLiteral("QLabel{color: rgb(170, 0, 0);}"));
同
ui->label1->setStyleSheet(QStringLiteral("QLabel{color: rgb(170, 0, 0);}"));
您不需要'myDialog.cpp'中的new Ui::myDialog
。
1)myDialog.h
添加#include "ui_mydialog.h"
更改Ui::myDialog* ui;
到Ui::myDialog ui;
2)myDialog.cpp
在构造函数中删除ui(new Ui::myDialog)
。
然后,您可以使用ui.label1->.....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.