【问题标题】:Problem with event handling on QToolButton in LinuxLinux中QToolButton上的事件处理问题
【发布时间】:2009-09-04 07:21:47
【问题描述】:

我正在开发一个应用程序,我在其中添加了一个 QToolBar 对象,并在其上添加了 QToolButton 对象,我还连接了 clicked() 事件,但问题是鼠标单击事件没有在 QToolButton 上工作,但是当我使用 Tab 将注意力集中在它上面时,空格按钮可以正常工作,但是我希望通过鼠标单击来实现它..有什么想法吗?这是代码。

pToolBar = new QToolBar(this);

pToolBar->setAllowedAreas(Qt::NoToolBarArea);//NoToolBarAreaAllToolBarAreas
pToolBar->setFloatable(false);
pToolBar->setGeometry(300,0,160,30);

QToolButton *playButton=new QToolButton(pToolBar);

playButton->setIcon(QIcon("/images/play.png"));

playButton->setGeometry(10,0,40,30);

playButton->setToolTip("Play/Pause");

connect(playButton, SIGNAL(clicked()),SLOT(playButtonClicked()));

【问题讨论】:

  • 点击按钮会发生什么?你的槽被调用了吗?
  • 不,它没有被调用..按钮的行为不像一个按钮,看起来它没有被点击..但是当我按下空格键时,它会被调用并且它工作正常

标签: c++ linux qt


【解决方案1】:

工具按钮通常在使用 QToolBar::addAction() 创建新的 QAction 实例或使用 QToolBar 将现有操作添加到工具栏时创建: :addAction()

例子:

QAction *newAct = new QAction(QIcon(":/images/new.png"), tr("&New"), this);
newAct->setShortcut(tr("Ctrl+N"));
newAct->setStatusTip(tr("Create a new file"));
connect(newAct, SIGNAL(triggered()), this, SLOT(newFile()));
fileToolBar = addToolBar(tr("File"));
fileToolBar->addAction(newAct);

你可以使用triggered信号,这个信号在给定动作被触发时发出。

你的例子:

QToolButton *playButton=new QToolButton(pToolBar);
connect(playButton, SIGNAL(triggered()),SLOT(playButtonClicked()));

【讨论】:

    【解决方案2】:

    尝试将工具按钮显式添加到工具栏。以下代码非常适合我:

    QToolBar *pToolBar = new QToolBar(this);
    
    QToolButton *playButton=new QToolButton(pToolBar);
    playButton->setIcon(QIcon("/images/play.png"));
    playButton->setText("Play");
    playButton->setToolTip("Play/Pause");
    playButton->setGeometry(10,0,40,30);
    
    QAction *a = pToolBar->addWidget(playButton);
    a->setVisible(true);
    
    connect(playButton, SIGNAL(clicked()),SLOT(playButtonClicked()));
    

    您可能应该将 QAction 指针保存在某处,因为这是分配键盘快捷键、启用/禁用按钮等的最简单方法。让我知道这是否适合您。如果没有,也许在这里发布一个完整的可编译示例将帮助我们帮助您。您应该能够获得一个小型演示程序,该程序可以在一两个文件中显示您的问题。

    干杯,

    【讨论】:

      【解决方案3】:

      正如 jordenysp 间接解释的那样,API 以 QAction 为中心

      【讨论】:

        猜你喜欢
        • 2019-08-03
        • 1970-01-01
        • 1970-01-01
        • 2015-04-18
        • 1970-01-01
        • 2012-04-30
        • 2011-05-16
        相关资源
        最近更新 更多