【问题标题】:clicked does not work when mousePressEvent and mouseReleaseEvent are overriden当 mousePressEvent 和 mouseReleaseEvent 被覆盖时,clicked 不起作用
【发布时间】: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


【解决方案1】:

当你重写一个方法时,你正在修改类的行为,在这种情况下,在 mouseReleaseEvent 中发出 clicked 信号,但只有在 mousePressEvent 接受事件时才会调用 mouseReleaseEvent,但在修改代码时你已经消除了它。解决方法是调用父类的实现。

void Button::mousePressEvent(QMouseEvent* event)
{
    setStyleSheet(defaultStyle + "Background-color: gray;");
    QPushButton::mousePressEvent(event);
}

void Button::mouseReleaseEvent(QMouseEvent* event) {
    setStyleSheet(defaultStyle + "Background-color: darkgray; border: 1px solid gray; color: white;");
    QPushButton::mouseReleaseEvent(event);
}

另一方面,我认为没有必要重写 mousePressEvent 方法,因为 Qt 样式表支持 pseudo-states:

setStyleSheet(R"(
    Button{
      // default styles
      background-color: darkgray; 
      border: 1px solid gray; 
      color: white;
    }
    Button::presed{
      // default styles
      background-color: gray;
    }
)");

【讨论】:

  • 非常感谢,:D 我也试过了,但是我使用了 QWidget::mousePressEvent() 并且没有用 :D
猜你喜欢
  • 1970-01-01
  • 2020-12-04
  • 1970-01-01
  • 2019-08-17
  • 1970-01-01
  • 2019-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多