[英]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.