c++ - "error: C2275: ' QMouseEvent ' : illegal use of this type as an expression"

标签 c++ qt qmouseevent

'我目前在尝试编译这个程序时遇到问题。该程序应该在 GUI QWidget 上显示鼠标的坐标 错误在mainwindow.cpp文件的第6行'

//header
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QApplication>
#include <QMainWindow>
#include <QMouseEvent>
#include <QMessageBox>
#include <QWidget>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow();

    void mouseReleaseEvent(QMouseEvent * event);

    ~MainWindow();

private:
    Ui::MainWindow *ui;

    QMessageBox *msgBox;
};

#endif // MAINWINDOW_H

' 主窗口.cpp文件'

    #include "mainwindow.h"
    #include "ui_mainwindow.h"

MainWindow::MainWindow()
{
   MainWindow::mouseReleaseEvent (QMouseEvent * event);
}

void MainWindow::mouseReleaseEvent(QMouseEvent * event)
{
    msgBox = new QMessageBox();
    msgBox -> setWindowTitle("Coordinates");
    msgBox -> setText("You released the button");
    msgBox -> show();
}

MainWindow::~MainWindow()
{
    delete ui;
}

'main.cpp'

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow *w = new MainWindow();

    w->setWindowTitle(QString::fromUtf8("QT-capture mouse release"));
            w->resize(300, 250);


    w->show();

    return a.exec();
}

请帮忙,我知道它与指针和可能的更改器(mutator)有关,但我还看不到。谢谢。

最佳答案

这是非法的:

MainWindow::MainWindow()
{
    // illegal:
    MainWindow::mouseReleaseEvent (QMouseEvent * event);
}

如果你想手动调用处理程序,你需要创建一个事件并传递它:

MainWindow::MainWindow()
{
    QMouseEvent event;
    MainWindow::mouseReleaseEvent(&event);
}

但是您随后需要正确设置 QMouseEvent 属性/如果不知道您为什么要这样做,很难说出如何设置。

你在做什么?这些事件会在鼠标事件时自动发出,您无需手动调用 mouseReleaseEvent,它会在您释放鼠标按钮时调用。

如果你想显示鼠标位置,我建议你:

  • mouseReleaseEvent替换为mouseMoveEvent
  • 只需删除您在 MainWindow::MainWindow()
  • 中的调用
  • MainWindow::mouseMoveEvent(QMouseEvent * event) 在主窗口的标签中写入鼠标坐标,而不是使用消息框(用鼠标坐标格式化 QString使用 QMouseEvent::pos 并使用 QLabel::setText)
  • 更改标签文本

像那样:

void MainWindow::mouseMoveEvent(QMouseEvent * event)
{ 
    std::stringstream str;
    str << "Mouse position is " << event->pos.x() << ";" << event->pos().y();
    ui->label->setText( str.str().c_str() );
}

关于c++ - "error: C2275: ' QMouseEvent ' : illegal use of this type as an expression",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33327095/

相关文章:

python - PyQt 中复选框的 ListView

qt - 如何连接到 mousePressEvent 插槽 Qt

c++ - qt按住鼠标按钮和定时器cpp

c++ - 指向用数组初始化的矩阵的指针数组

c++ - 嵌套类指针的特殊行为?

c++ - 重构期间结构的聚合初始化是否安全?

c++ - 不寻常的 static_cast 语法

c++ - QTableWidget 在不处于焦点时挂起/暂停

c++ - Qt C++ QLabel 可点击鼠标事件不起作用

python - 如何在布局中的小部件之间捕获 mousePressEvent?