gpt4 book ai didi

c++ - 如何以编程方式更改 Qt 中按钮的样式表?

转载 作者:行者123 更新时间:2023-11-30 04:53:04 24 4
gpt4 key购买 nike

我在一个对话框上有很多按钮,我想在某些情况下更改它们的样式表。按钮对象名称如下:
btn_1
btn_2
btn_3
..
btn_20


当我点击其中一个数字按钮然后又点击另一个简单按钮时,我想更改第一个点击的数字按钮样式表。如何访问所选的数字按钮?

编辑:图片是什么意思
buttons


我正在尝试使用右列按钮设置左列按钮(具有按数字排序的对象名称)的颜色。用户将首先点击数字按钮,然后点击颜色命名按钮。

最佳答案

您必须使用 setStyleSheet 方法,但必须保持按下按钮的引用,这可以使用返回发出信号的对象的 sender 方法来完成。

#include <QtWidgets>

class MainWindow: public QMainWindow{
Q_OBJECT
public:
MainWindow(QWidget *parent=nullptr):
QMainWindow(parent),
current_button(nullptr)
{
QWidget *widget = new QWidget;
setCentralWidget(widget);
QHBoxLayout *hlay = new QHBoxLayout(widget);
QVBoxLayout *number_lay = new QVBoxLayout;
QVBoxLayout *color_lay = new QVBoxLayout;
hlay->addLayout(number_lay);
hlay->addLayout(color_lay);

for(int i=0; i<20; i++){
QPushButton *button = new QPushButton(QString("btn_%1").arg(i+1));
connect(button, &QPushButton::clicked, this, &MainWindow::number_clicked);
number_lay->addWidget(button);
}
color_lay->addStretch();
for(const QString & colorname: {"Red", "Green", "Blue"}){
QPushButton *button = new QPushButton(colorname);
connect(button, &QPushButton::clicked, this, &MainWindow::color_clicked);
color_lay->addWidget(button);
button->setProperty("color", colorname.toLower());
button->setStyleSheet(QString("background-color: %1").arg(colorname));
}
color_lay->addStretch();
}
private slots:
void number_clicked(){
current_button = qobject_cast<QPushButton *>(sender());
}
void color_clicked(){
if(current_button){
QString colorname = sender()->property("color").toString();
current_button->setStyleSheet(QString("background-color: %1").arg(colorname));
}
}
private:
QPushButton *current_button;
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();

return a.exec();
}
#include "main.moc"

enter image description here

关于c++ - 如何以编程方式更改 Qt 中按钮的样式表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53992219/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com