'我目前在尝试编译这个程序时遇到问题。该程序应该在 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/