自己写了一个mypushbutton类继承qpushbutton,mypushbutton的布局中有一个qlabel,需要设置mypushbutton选中和未选中时的qlabel字体颜色
3条回答 默认 最新
- Kwan的解忧杂货铺@新空间代码工作室 2024-03-15 14:15关注
把嘎嘎 下午好🌅🌅🌅
本答案参考ChatGPT-3.5要设置mypushbutton选中和未选中时的qlabel字体颜色,可以通过在mypushbutton中重写其选中状态的paintEvent函数,并在其中设置qlabel的字体颜色。
下面是一种可能的解决方案:
1.在mypushbutton.h头文件中,添加一个成员变量来保存选中和未选中时的字体颜色:
class MyPushButton : public QPushButton { Q_OBJECT public: explicit MyPushButton(QWidget *parent = nullptr); void setSelectedColor(const QColor &color); void setUnselectedColor(const QColor &color); protected: void paintEvent(QPaintEvent *event) override; private: QColor selectedColor; QColor unselectedColor; };
2.在mypushbutton.cpp文件中,实现setSelectedColor和setUnselectedColor函数,以及重写的paintEvent函数:
MyPushButton::MyPushButton(QWidget *parent) : QPushButton(parent) { // 设置默认的选中和未选中时的字体颜色 selectedColor = Qt::red; unselectedColor = Qt::black; } void MyPushButton::setSelectedColor(const QColor &color) { selectedColor = color; } void MyPushButton::setUnselectedColor(const QColor &color) { unselectedColor = color; } void MyPushButton::paintEvent(QPaintEvent *event) { QPushButton::paintEvent(event); // 获取按钮的状态 QStyleOptionButton option; initStyleOption(&option); bool selected = option.state & QStyle::State_On; // 设置qlabel的字体颜色 QLabel *label = qobject_cast<QLabel*>(this->layout()->itemAt(0)->widget()); if (label) { if (selected) { label->setStyleSheet("color: " + selectedColor.name() + ";"); } else { label->setStyleSheet("color: " + unselectedColor.name() + ";"); } } }
3.在使用mypushbutton的地方,可以通过调用setSelectedColor和setUnselectedColor函数来设置选中和未选中时的字体颜色:
MyPushButton *button = new MyPushButton(this); button->setText("Button"); button->setSelectedColor(Qt::blue); button->setUnselectedColor(Qt::black);
这样,在按钮被选中时,qlabel的字体颜色将会变为蓝色,未选中时为黑色。
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 鼠标右键,撤销删除 复制 移动,要怎样删除
- ¥15 使用MATLAB进行余弦相似度计算加速
- ¥15 服务器安装php5.6版本
- ¥15 我想用51单片机和数码管做一个从0开始的计数表 我写了一串代码 但是放到单片机里面数码管只闪烁一下然后熄灭
- ¥20 系统工程中,状态空间模型中状态方程的应用。请猛男来完整讲一下下面所有问题
- ¥15 我想在WPF的Model Code中获取ViewModel Code中的一个参数
- ¥15 arcgis处理土地利用道路 建筑 林地分类
- ¥20 使用visual studio 工具用C++语音,调用openslsx库读取excel文件的sheet问题
- ¥100 寻会做云闪付tn转h5支付链接的技术
- ¥15 DockerSwarm跨节点无法访问问题