wxWidgets 拖放文件事件处理程序初始化问题(无效static_cast)

wxWidgets Drop Files eventhandler initialization problem (invalid static_cast)

本文关键字:static 无效 cast 问题 文件 拖放 事件处理 程序 初始化 wxWidgets      更新时间:2023-10-16

我正在尝试制作一个简单的程序,使用带有(wxWidgets(wxListCtrl的C++将文件拖放到列表中。

  • 我使用的工具:代码::块20.03,MinGW 17.1,wxWidgets 3.1.3,wxFormBuilder 3.9.0。
  • 操作系统:视窗 10 专业版。

我尝试了以下内容:(在DnD_SimpleFrame类构造函数中调用的函数 SetupGUI(( 中。

m_listCtrl1 = new wxListCtrl( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLC_NO_HEADER|wxLC_REPORT );
m_listCtrl1->DragAcceptFiles(true);
m_listCtrl1->Connect(wxEVT_DROP_FILES, wxDropFilesEventHandler(DnD_SimpleFrame::OnDropFiles), NULL, this);

删除文件(从资源管理器(时要调用的函数是:

bool DnD_SimpleFrame::OnDropFiles(wxArrayString &filenames)
{
size_t nFiles = filenames.GetCount();
wxString str;
str.Printf( "%d files dropped", (int)nFiles);
m_listCtrl1->DeleteAllItems();
if (m_listCtrl1 != NULL)
{
m_listCtrl1->InsertItem(0, str);
for ( size_t n = 1; n < (nFiles+1); n++ )
m_listCtrl1->InsertItem(n, filenames[n]);
}
return true;
}

m_listCtrl1->Connect(...(; 行上的生成消息是:

||=== Build: Debug in DnD_Simple (compiler: GNU GCC Compiler) ===|
F:Data__C++wxAppsDnD_SimpleDnD_SimpleMain.cpp||In member function 'void DnD_SimpleFrame::SetupGUI()':|
F:SDKswx313includewxevent.h|149|error: invalid static_cast from type 'bool (DnD_SimpleFrame::*)(wxArrayString&)' to type 'wxDropFilesEventFunction' {aka 'void (wxEvtHandler::*)(wxDropFilesEvent&)'}|
F:SDKswx313includewxevent.h|4196|note: in expansion of macro 'wxEVENT_HANDLER_CAST'|
F:Data__C++wxAppsDnD_SimpleDnD_SimpleMain.cpp|92|note: in expansion of macro 'wxDropFilesEventHandler'|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 1 second(s)) ===|

我在这里做错了什么(或忘记了(?

如果您仔细查看错误消息:

error: invalid static_cast from type 'bool (DnD_SimpleFrame::*)(wxArrayString&)' to type 'wxDropFilesEventFunction' {aka 'void (wxEvtHandler::*)(wxDropFilesEvent&)'}

你可以看到它说它不能将某些东西从一种类型转换为另一种类型。

如果您不熟悉C++,则可能难以分析这些类型,但您应该能够看到这些是函数指针(实际上是指向类成员的指针(。查看您的代码,您还应该能够看到第一个是您的DnD_SimpleFrame::OnDropFiles函数的类型,因此问题是它无法转换为预期的函数类型。

最后,这样做的原因只是你的函数没有正确的参数类型:你应该给wxWidgets一些需要wxDropFilesEvent&的东西,但你的函数需要wxArrayString&。您必须更改它以获取wxDropFilesEvent& event然后使用事件对象GetFiles()方法来获取实际文件。


在完全不同的主题上,您应该在新代码中使用Bind()而不是Connect()。如果您遵循使用后者的教程,则表明它已经过时了。您的代码仍然不会使用Bind()进行编译,但错误消息会稍微简单一些。