Finding a wxMenu's Selected Radio Item - c++

Let's say that I have a group of radio items in a wxMenu. I know that exactly one of these will be checked at any given time.
Does the wxMenu or some other construct hold onto the index of the checked item, or do I need to call the isChecked on each radio item till I find the checked element to find it's index?
I've asked this question about how to do that, but I'd much prefer wxWidgets saved me from doing that everywhere.

No, saving the index of the last selected item (as shown in ravenspoint's answer) or using wxMenuBarBase::IsChecked() until you find the selected radio button is the only way to do it.
For wxWidgets to provide access to the currently selected button it would need not only to store it (which means not forgetting to update not only when the selected changes, but also when items are inserted into/deleted from the menu, so it's already not completely trivial), but to somehow provide access to the radio items group you're interested in, which would require being able to identify it and currently there is no way to do it and adding it isn't going to be particularly simple.
What could be done easily, however, is writing a reusable function int GetIndexOfSelectedRadioItem(int firstItem) that would start at the given item and call IsChecked() on subsequent items until it returns true and return the offset of the item. You should be able to do it in your own code, but if you'd like to include such function in wxWidgets itself (as a static wxMenuBar method, probably), please don't hesitate to send patches/pull requests doing it!

It is easy enough to roll your own.
Bind an event handler to wxEVT_COMMAND_RADIOBUTTON_SELECTED for every button. In the handler, extract the ID of the selected radio button and store it somewhere.
Like this:
ResolMenu = new wxMenu();
ResolMenu->AppendRadioItem(idRcvLoRez,"Low Resolution");
ResolMenu->AppendRadioItem(idRcvMeRez,"Medium Resolution");
ResolMenu->AppendRadioItem(idRcvHiRez,"High Resolution");
ResolMenu->Check( idRcvLoRez, true );
Bind(wxEVT_MENU,&cFrame::onRcvRez,this,idRcvLoRez);
Bind(wxEVT_MENU,&cFrame::onRcvRez,this,idRcvMeRez);
Bind(wxEVT_MENU,&cFrame::onRcvRez,this,idRcvHiRez);
void onRcvRez( wxCommandEvent& event )
{
myRezID = event.GetId();

Related

C++ Windows Owner Drawn Main Menu -- itemID

I am attempting to create an owner-drawn main menu, in Windows. I understand setting:
menuiteminfo.ftype = MFT_OWNERDRAW
I also know about handling the WM_MEASUREITEM and WM_DRAWITEM messages.
However, how do I know which main menu item is sending the message? (so that I can fill-in the appropriate box size and text) "itemID" seems to be the only unique identifier. But, how can I associate this pointer/handle to the item in question? I can use "lParam" to determine it is a menu item. But, I can't determine which menu item. "GetMenuItemID" is useless, as it returns "-1" for all main-menu items.
Or, am I going about this all-wrong? I have been searching for answers, for weeks. Really, all I want to do is change the text color of the main menu, from black, to white or light gray, so I can use a dark background.
The itemID field of the MEASUREITEMSTRUCT and DRAWITEMSTRUCT structs tells you exactly which menu item is being measured/drawn. This is the ID that you specify when you create/modify a menu item. That ID is specified via either:
the uIDNewItem parameter of AppendMenu(), InsertMenu(), or ModifyMenu().
the item parameter of InsertMenuItem() or SetMenuItemInfo()
the wID field of the MENUITEMINFO struct that you pass to InsertMenuItem() or SetMenuItemInfo().
Use whatever IDs you want, as long as they are unique for your menus.
You can also use the itemData field of MEASUREITEMSTRUCT and DRAWITEMSTRUCT to receive any custom data you want for owner-drawn menu items, if you so desire (like, for example, a pointer to a buffer that contains a menu item's text string). This custom value can be anything you want that is meaningful for you. You set this value in the dwItemData field of the MENUITEMINFO struct that you pass to InsertMenuItem() or SetMenuItemInfo().
This is all covered in the documentation:
Using Menus: Creating Owner Drawn Menu Items
Thank you Remy. Through the items that you mentioned, and researching the documentation for each, I was able to find a buried secret. For a Main Menu item, the "itemID" in both the MEASUREITEMSTRUCT and DRAWITEMSTRUCT is the handle to the drop-down menu of that item. From that, I added this line of code to WM_CREATE, to associate the itemID with the numerical (zero-based) position:
mItemID[i] = int(GetSubMenu(hMenu, i));
'i' is the numerical position, from left to right. I can then use a comparison statement like this, in WM_MEASUREITEM and WM_DRAWITEM:
lpmis=(LPMEASUREITEMSTRUCT)lParam; if(lpmis->itemID==mItemID[i])

QTreeWidgetItem setting not selectable clears the selection

I have a QTreeWidget and I want certain rows to be non select-able, which can be achieved by QTreeWidgetItem::setFlags(treeWidgetItem->flags() & ~Qt::ItemIsSelectable).
The problem is that I have an existing row that is already selected and later I click on the non select-able row, selectedItems() returns an empty list. I want the selected row to keep its selection if the user tries to select a non select-able row.
Should I keep track of the selection and handle this scenario in the code, or this can be achieved somehow else. I'd rather not reinvent the wheel.
Thank you.
Cause
Calling QTreeView::mousePressEvent(event) clears the selection when clicked on a non-selectable item if the selection mode is set to QAbstractItemView::SingleSelection.
Solution
My solution would be to either:
Set the selection mode to QAbstractItemView::MultiSelection,
or (in case this is not desired):
Reimplement the mouse events in a subclass of QTreeWidget in order to bypass the default behavior.
Note: In either case, use the QItemSelectionModel::selectionChanged signal to get the list of the selected items.
Example
Here is an example re-implementation of the mouse events in MyTreeWidget preventing the selection of being cleared by clicking a non-selectable item. The top item is expanded/collapsed on a double click:
void MyTreeWidget::mousePressEvent(QMouseEvent *event)
{
if (indexAt(event->pos())->flags() & Qt::ItemIsSelectable)
QTreeWidget::mousePressEvent(event);
}
void MyTreeWidget::mouseDoubleClickEvent(QMouseEvent *event)
{
QTreeWidget::mouseDoubleClickEvent(event);
QTreeWidgetItem *item = itemAt(event->pos());
if (item && item->childCount())
item->setExpanded(!item->isExpanded());
}
The modified in the described manner version of the provided example is available on GitHub.
Improvements
Special thanks to #eyllanesc for making this example more waterproof by:
adding a check if item is not NULL
replacing itemAt with indexAt

How do I poll a set of RadioButton widgets in tkd (Tinker for the D language)

I've made a block of RadioButton widgets for my tkd interface, which work exactly as expected. However, the documentation for tkd's RadioButton doesn't show how one determines which of the buttons is pressed. Instead, the example code simply shows how to create an array of buttons that are linked together (i.e. so that only one can be selected at a time)
// The radio button group parent.
auto frame = new Frame()
.pack();
auto option1 = new RadioButton(frame, "Foo")
.setSelectedValue("foo")
.select()
.pack();
auto option2 = new RadioButton(frame, "Bar")
.setSelectedValue("bar")
.pack();
The CheckButton widget is a similar, and can be polled withe its associated isChecked() method, but nothing similar seems to be present for the RadioButton.
How do I check whether a given RadioButton has been selected?
Additionally, is there an easy way to check which member of an array of RadioButtons is selected, without iterating over the entire set myself?
After reading more documentation, it appears tkd implements this feature with a series of mixins.
The RadioButton class implements the Value interface described here.
Calling any of the associated methods will allow access to the state variable that is shared by the entire button array. E.g.
option1.getValue(); // Returns "Foo" if option 1 is selected, "Bar" if option 2 is.
option2.getValue(); // Same as above, since the value is shared.
option2.setValue("bar"); //Change value, without changing the selected button.

Using images in QListWidget, is this possible?

I am using QT to create a chat messenger client. To display the list of online users, I'm using a QListWidget, as created like this:
listWidget = new QListWidget(horizontalLayoutWidget);
listWidget->setObjectName("userList");
QSizePolicy sizePolicy1(QSizePolicy::Preferred, QSizePolicy::Expanding);
sizePolicy1.setHorizontalStretch(0);
sizePolicy1.setVerticalStretch(0);
sizePolicy1.setHeightForWidth(listWidget->sizePolicy().hasHeightForWidth());
listWidget->setSizePolicy(sizePolicy1);
listWidget->setMinimumSize(QSize(30, 0));
listWidget->setMaximumSize(QSize(150, 16777215));
listWidget->setBaseSize(QSize(100, 0));
listWidget->setContextMenuPolicy(Qt::CustomContextMenu);
Users are shown by constantly refreshing the list, like this: (Note: There are different channels, with different userlists, so refreshing it is the most efficient thing to do, as far as I know.)
void FMessenger::refreshUserlist()
{
if (currentPanel == 0)
return;
listWidget = this->findChild<QListWidget *>(QString("userList"));
listWidget->clear();
QList<FCharacter*> charList = currentPanel->charList();
QListWidgetItem* charitem = 0;
FCharacter* character;
foreach(character, charList)
{
charitem = new QListWidgetItem(character->name());
// charitem->setIcon(QIcon(":/Images/status.png"));
listWidget->addItem(charitem);
}
}
This has always worked perfectly. The line that I commented out is the one I have problems with: my current goal is to be able to display a user's online status with an image, which represents whether they are busy, away, available, etc. Using setIcon() does absolutely nothing though, apparently; the items still show up as they used to, without icons.
I'm aware that this is probably not the way this function needs to be used, but I have found little documentation about it online, and absolutely no useful examples of implementations. My question is, can anybody help me with fixing this problem?
This is how you may conduct your debugging:
Try the constructor that has both icon and text as arguments.
Try to use that icon in another context to ensure it is displayable (construct a QIcon with same argument and use it elsewhere, e.g. QLabel!).
Use icon() from the QListWidgetItem to receive back the icon and then look at that QIcon.
Create a new QListWidget, change nothing, and ordinarily add some stock items in your MainWidget's constructor. See if the icons show up there.

Programmatically change combobox

I need to update a combobox with a new value so it changes the reflected text in it. The cleanest way to do this is after the comboboxhas been initialised and with a message.
So I am trying to craft a postmessage to the hwnd that contains the combobox.
So if I want to send a message to it, changing the currently selected item to the nth item, what would the postmessage look like?
I am guessing that it would involve ON_CBN_SELCHANGE, but I can't get it to work right.
You want ComboBox_SetCurSel:
ComboBox_SetCurSel(hWndCombo, n);
or if it's an MFC CComboBox control you can probably do:
m_combo.SetCurSel(2);
I would imagine if you're doing it manually you would also want SendMessage rather than PostMessage. CBN_SELCHANGE is the notification that the control sends back to you when the selection is changed.
Finally, you might want to add the c++ tag to this question.
A concise version:
const int index = 0;
m_comboBox.PostMessage(CBN_SELCHANGE, index);
What might be going wrong is the selection is being changed inside the selection change message handler, which result in another selection change message.
One way to get around this unwanted feedback loop is to add a sentinel to the select change message handler as shown below:
void onSelectChangeHandler(HWND hwnd)
{
static bool fInsideSelectChange = 0;
//-- ignore the change message if this function generated it
if (fInsideSelectChange == 0)
{
//-- turn on the sentinel
fInsideSelectChange = 1;
//-- make the selection changes as required
.....
//-- we are done so turn off the sentinel
fInsideSelectChange = 0;
}
}
if you fx want to change the title - which is the line shown when combobox is closed, then you can do following:
m_ComboBox.DeleteString(0); // first delete previous if any, 0 = visual string
m_ComboBox.AddString(_T("Hello there"));
put this in fx. in OnCloseupCombo - when event close a dropdownbox fires
ON_CBN_CLOSEUP(IDC_COMBO1, OnCloseupCombo)
This change is a new string not a selection of already assigned combobox elements