【发布时间】:2019-09-25 19:48:03
【问题描述】:
所以我想为我的按钮添加一些样式。所以我创建了一个派生自 QPushButton 的类。我已经覆盖了 mousePressEvent 和 mouseReleaseEvent 函数。到目前为止,一切都很好。一切都按预期工作,按钮在按下和释放时会改变颜色。 问题来了当在我的MainWindow中我尝试实现on_button_clicked()。它只是行不通。
我对 event->accept 和 event->ignore 做了一些实验。那没用。
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
void MainWindow::on_characters_clicked()
{
qDebug("Hello");
}
void Button::mousePressEvent(QMouseEvent* event)
{
setStyleSheet(defaultStyle + "Background-color: gray;");
}
void Button::mouseReleaseEvent(QMouseEvent* event) {
setStyleSheet(defaultStyle + "Background-color: darkgray; border: 1px solid gray; color: white;");
}
我希望我的按钮在按下和释放时具有两种样式以及功能。我可以编写一个观察者类来解决这个问题,但我觉得必须有一个更简单的解决方案。
【问题讨论】:
-
您覆盖了鼠标按下/释放功能,而不是将调用传播到父类,父类可能也关心点击事件。如果您尝试从重写的函数中相应地调用
QPushButton::mousePressEvent(event);和QPushButton::mouseReleaseEvent(event);会怎样?
标签: qt