QT中自定义widget1和自定义widget2,自定义widget1中包括按钮和标签,点击自定义widget1界面时,widget1的边框颜色发生变化;点击自定义widget1的按钮时,创建一个自定义widget2的界面
时间: 2024-02-12 20:07:07 浏览: 98
自定义的widget
3星 · 编辑精心推荐
首先,你需要创建两个自定义widget类,分别为CustomWidget1和CustomWidget2,并在其中添加你需要的控件,如按钮和标签等。
然后在CustomWidget1中,重载鼠标点击事件的函数,当点击CustomWidget1时,改变CustomWidget1的边框颜色。具体实现代码如下:
```cpp
void CustomWidget1::mousePressEvent(QMouseEvent *event)
{
Q_UNUSED(event);
QPalette pal = this->palette();
pal.setColor(QPalette::Window, QColor(Qt::red)); // 将窗口颜色设置为红色
this->setPalette(pal);
}
```
在自定义的按钮的槽函数中,创建CustomWidget2的实例,并显示出来。具体实现代码如下:
```cpp
void CustomWidget1::onButtonClicked()
{
CustomWidget2 *widget2 = new CustomWidget2(this);
widget2->show();
}
```
最后,在主程序中,将CustomWidget1添加到窗口中即可。完整的示例代码如下:
```cpp
// CustomWidget1.h
#include <QWidget>
class CustomWidget1 : public QWidget
{
Q_OBJECT
public:
explicit CustomWidget1(QWidget *parent = nullptr);
protected:
void mousePressEvent(QMouseEvent *event) override;
private slots:
void onButtonClicked();
private:
QPushButton *m_button;
QLabel *m_label;
};
// CustomWidget1.cpp
#include "CustomWidget1.h"
#include "CustomWidget2.h"
CustomWidget1::CustomWidget1(QWidget *parent) : QWidget(parent)
{
m_button = new QPushButton("Click me", this);
m_label = new QLabel("Hello world", this);
connect(m_button, &QPushButton::clicked, this, &CustomWidget1::onButtonClicked);
}
void CustomWidget1::mousePressEvent(QMouseEvent *event)
{
Q_UNUSED(event);
QPalette pal = this->palette();
pal.setColor(QPalette::Window, QColor(Qt::red)); // 将窗口颜色设置为红色
this->setPalette(pal);
}
void CustomWidget1::onButtonClicked()
{
CustomWidget2 *widget2 = new CustomWidget2(this);
widget2->show();
}
// CustomWidget2.h
#include <QWidget>
class CustomWidget2 : public QWidget
{
Q_OBJECT
public:
explicit CustomWidget2(QWidget *parent = nullptr);
};
// CustomWidget2.cpp
#include "CustomWidget2.h"
CustomWidget2::CustomWidget2(QWidget *parent) : QWidget(parent)
{
QLabel *label = new QLabel("This is CustomWidget2", this);
}
// main.cpp
#include <QApplication>
#include "CustomWidget1.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
CustomWidget1 widget1;
widget1.show();
return a.exec();
}
```
阅读全文