I am new in QT. I have 8 QT QPushButton like in this image.
Requirement
After clicking any button its border is highlighted with a black circle. The highlighted border should disappear only when any new button among the 8 is clicked and a black circle should encircle around that new button at run time.
Note: Circle should encircle around one button at a time which is clicked.
Attempt:
I am made the red circle using this code in QT form class
button1->setStyleSheet("QPushButton {background-color: rgb(200,0,0),border-radiu:15px}") ;
In button clicked slot I am
void button1clicked()
{
button1->setStyleSheet("QPushButton {border-style:solid; border-width:3px; border-color:black;}") ;
}
How do change the style sheet for a second time?
I have visited this
CodePudding user response:
Seems you're setting styleSheet to your window, not button's itself. So try this one:
button1->setStyleSheet("background-color: rgb(200,0,0); border-radius: 15px;");
button1->setStyleSheet(button1->styleSheet().append(QString("border-style:solid; border-width:3px; border-color:black;")) );
UPDATED: Here's one way that works:
mainwindow.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QSignalMapper>
#include <QPushButton>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void buttonClicked(QObject* object);
private:
Ui::MainWindow *ui;
QSignalMapper* signalMapper;//to handle signals
//previous clicked button
QPushButton* clickedButton;
};
#endif // MAINWINDOW_H
mainwindow.cpp:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
//we are gonna use signal mapper
//since we have 8 buttons on UI
//to avoid working with every button
signalMapper = new QSignalMapper(this);
for(int i = 1; i <= 8; i)
{
QPushButton* btn = this->findChild<QPushButton*>("button"
QString::number(i));
btn->setStyleSheet("background-color: red;"
"border-radius: 5px;");
connect(btn, SIGNAL(clicked()),
signalMapper, SLOT(map()));
signalMapper->setMapping(btn, btn);
}
connect(signalMapper, SIGNAL(mappedObject(QObject*)),
this, SLOT(buttonClicked(QObject*)));
//by default, we take 1st button as marked
clickedButton = ui->button1;
clickedButton->setStyleSheet("background-color: red;"
"border: 3px solid black;"
"border-radius: 5px;");
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::buttonClicked(QObject *object)
{
QPushButton* btn = qobject_cast<QPushButton*>(object);
QString temp = btn->styleSheet();
btn->setStyleSheet(clickedButton->styleSheet());
clickedButton->setStyleSheet(temp);
clickedButton = btn;
}
UI contains 8 buttons from button1 to button8.