[英]How to add buttons to a main window by programmatically in Qt and change styles them by use css file?
我将在对话框中添加两个按钮,我想通过使用 css 文件更改它们的样式表:
我还定义了如下不起作用的按钮:
sendButton = new QPushButton();
sendButton->setVisible(true);
sendButton->setText("sendButton");
sendButton->setStyleSheet("QPushButton#sendButton {\n"
"background-color: red;\n"
"border-style: outset;\n"
"border-width: 2px;\n"
"border-radius: 10px;\n"
"border-color: beige;\n"
"font: bold 14px;\n"
"min-width: 10em;\n"
"padding: 6px;\n"
"}\n"
"QPushButton#reciveButton {\n"
"background-color: green;\n"
"border-style: outset;\n"
"border-width: 2px;\n"
"border-radius: 10px;\n"
"border-color: beige;\n"
"font: bold 14px;\n"
"min-width: 10em;\n"
"padding: 6px;\n"
"}\n");
ui->horizontalLayout->addWidget(sendButton);
如果您使用ID 选择器QPushButton#objectName
objectName ,请务必同时为您的 QPushButton 设置 object 名称,否则选择器将不起作用
sendButton = new QPushButton();
sendButton->setVisible(true);
sendButton->setText("sendButton");
sendButton->setObjectName("sendButton"); /* Set the object name */
sendButton->setStyleSheet(...);
希望这会有所帮助=)
要以编程方式将任何小部件添加到 window (MainWindow, Dialog, ...),您必须执行以下操作:
例如:
//Step 1: create widgets
QPushButton *sendbtn = new QPushButton("sendButton");
sendbtn->setObjectName("mySendButton");
QPushButton *receivebtn = new QPushButton("receiveButton");
receivebtn->setObjectName("myReceiveButton");
//Step 2: create a layout
QHBoxLayout *hlayout = new QHBoxLayout;
//Step 3: add widgets to the layout
hlayout->addWidget(sendbtn);
hlayout->addWidget(receivebtn);
QWidget *w = new QWidget;
w->setLayout(hlayout);
setCentralWidget(w);
setStyleSheet("QPushButton#mySendButton"
"{"
"background-color: red;"
"border-style: outset;"
"border-width: 2px;"
"border-radius: 10px;"
"border-color: beige;"
"font: bold 14px;"
"min-width: 10em;"
"padding: 6px;"
"}"
"QPushButton#myReceiveButton"
"{"
"background-color: green;"
"border-style: outset;"
"border-width: 2px;"
"border-radius: 10px;"
"border-color: beige;"
"font: bold 14px;"
"min-width: 10em;"
"padding: 6px;"
"}");
output如下:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.