"Smart" Linked Scrollbar and Edit Controls? - c++

I hope that I can explain my problem well enough for someone to help.
Basically, I have a horizontal scrollbar (ranged 0 to 1000) and an edit control that represents the position of the scrollbar divided by 1000, so that the user can use either the scrollbar to select a range of numbers between 0 and 1 up to a 3 decimal precision (.001, .002, ..., .987, etc.), or enter their own number in the edit box. As they scroll the scrollbar, the number in the edit control changes to reflect the new scroll position. When a new number is entered, the scrollbar sets itself to a new position reflecting the number entered. Meanwhile I also perform some calculations with this number as it changes (through either the scrollbar or the edit control) and display the results in another dialog.
Here is my problem: I'm having trouble deciding which event handlers to use to produce the proper behavior when a user enters a number into the edit control.
I'm using a double value variable called fuelMargin to handle my edit control and a CScrollBar control variable called fuelScroll to handle the scrollbar.
In my HSCROLL event I set the edit control to the scroll position / 1000. No problems there; when the user scrolls the scrollbar the edit box is correctly updated.
As for the edit box, my first attempt was an ONCHANGE event:
void MarginDlg::OnEnChangeFueledit()
{
CEdit* editBox;
editBox = (CEdit*)GetDlgItem(IDC_FUELEDIT);
CString editString;
editBox->GetWindowText(editString);
if (editString.Compare(".") != 0 && editString.Compare("0.") != 0
&& editString.Compare(".0") != 0 && editString.Compare("0.0") != 0
&& editString.Compare(".00") != 0 && editString.Compare("0.00") != 0)
{
UpdateData();
UpdateData(FALSE);
if (fuelMargin > 1)
{
UpdateData();
fuelMargin = 1;
UpdateData(FALSE);
}
if (fuelMargin < 0)
{
UpdateData();
fuelMargin = 0;
UpdateData(FALSE);
}
fuelScroll.SetScrollPos(int(fuelMargin*1000));
}
}
I needed that first if statement in there to keep from doing an UpdateData() when the user is trying to type a number like .5 or .05 or .005. It does produce a few wonky behaviors, though; when the user tries to type something like .56, after the .5 an UpdateData() is performed, the number becomes 0.5, and the cursor is moved to the far left, so if they tried to type .56 they would accidentally end up typing 60.5 -- which goes to 1, since I won't let them enter numbers lower than 0 or higher than 1. If they enter 0.56, however, this behavior is avoided.
For my second attempt, I commented out my ONCHANGE event and put in an ONKILLFOCUS event instead:
void MarginDlg::OnEnKillfocusFueledit()
{
UpdateData();
UpdateData(FALSE);
if (fuelMargin > 1)
{
UpdateData();
fuelMargin = 1;
UpdateData(FALSE);
}
if (fuelMargin < 0)
{
UpdateData();
fuelMargin = 0;
UpdateData(FALSE);
}
fuelScroll.SetScrollPos(int(fuelMargin*1000));
}
So now the user can finish typing their number and all is hunky dory--as long as they click out of the edit box. The scrollbar won't move and results won't be calculated until the box loses focus.
I want the results to be calculated as the numbers in the box are being typed; I want the scrollbar to move as the numbers are being typed. But I don't want typing to be disrupted, i.e. the actual numbers in the box changed or the cursor moved in any way.
Suggestions?
Thanks!

With the first approach, it looks like you're almost there: the only really significant problem is that the repeated calls to UpdateData() mess with the cursor position as the user is typing.
Given that you're trying to have a reasonably complex interaction between the controls, what I'd suggest is not to do validation in the OnChange() at all, so that as the user is typing he can type what he wants (which is how most numeric edit controls work anyway). When the user closes the dialog the controls are on (or clicks a button that uses the data in some way) then validation should be triggered, and a suitable error shown.
Once you're free from validating in OnChange(), you can fix the "cursor moves" problem by simply not calling UpdateData() in OnChange(). Instead, just parse the number from "editString" and, if it's in the valid range, update the scrollbar. That way, the scrollbar updates as the user types, and if they type in an invalid value the scrollbar stays put, and they'll get an error when they move to whatever the next stage is. Something like this (not tested):
void MarginDlg::OnEnChangeFueledit()
{
CString editString;
GetDlgItem(IDC_FUELEDIT)->GetWindowText(editString);
double editValue;
if ((sscanf(editString,"%lf",&editValue) == 1)
{
if (editValue >= 0.0) && (editValue <= 1.0))
fuelScroll.SetScrollPos(int(editValue*1000));
}
}
The only remaining important problem to note is that, if the user types some invalid value, or a number out of the valid range, then the edit control and the scrollbar will be out of sync. The simplest way to deal with that is to just decide that the edit control is the "master" value: that is, when we want to know what the user entered, we always look at the edit control, not the scrollbar, and validate data.
As for your second approach, one possible solution might be to implement a timer message handler: in the timer handler you could say the equivalent of "if the user hasn't typed anything for a second, I'll assume they're done, and parse the number and update the scrollbar". I'm not so keen on that as a solution, though.

I'd suggest watching for the Enter key, and performing UpdateData() then as well as OnKillFocus and OnChange. The more user-friendly the better.
Next, make sure your UpdateData() routine only works in the direction you need:
If ".5" is entered in the edit control, run your UpdateData() routine when the OnChange event is raised, but make sure to update your scrollbar only. Don't worry about updating the edit control to "0.5" until OnKillFocus is raised. Any updates in the reverse direction (to the edit control) will mess with your cursor. If your edit control is somehow bound to this double variable and auto updates when the var changes, consider leaving the double and your edit control seperate from each other until the OnKillFocus event is raised.
The same concept applies in the other direction as well. When the user scrolls, don't mess with the scrollbar. Just update the edit control and leave it at that.
I should add that XAML's data-binding features really help in situations like this, if you know how to use them properly. It's unfortunate for us native-type developers that it's so difficult to implement similar functionality using only event handlers.

Related

CMFCOutlookBarTabCtrl::SetActiveTab not working

I have added a CMFCOutlookBar control to a dialog. This outlookbar contains some 12 trees.
As per following link https://msdn.microsoft.com/en-us/library/bb983453.aspx
we can set active tab (in my case tree control) of our wish.
but it doesn't seems to work.
as per above link this function returns non zero value on success. Indeed it is returning 1 when i used it to set tree of my choice. but visually it's not changed.
can someone help me?
Problem solved.
CMFCOutlookBarTabCtrl::SetActiveTab() only works after window has been displayed.
I guess this is because CMFCOutlookBar stores it's previous state to registory and reloads on next run. And this overrides changes made by SetActiveTab(), if we use it before displaying of window.
I had the same problem, and you are correct that on load the tab gets set to the last session value - actually it seems to get set several times during the load process - some of them seem to correspond to each time a tab is added, and then the last time it is called seems to be the tab from the previous session.
The solution is to set the value once the window is ready to be shown. This can be done by overriding the OnShowWindow callback on the view which contains the tab bar.
In my case the tab bar is added in a view called MainFrame, which has a member variable CMFCOutlookBarTabCtrl* m_pOutlookBar; which is initialised in the OnCreate callback.
I can then correctly set the tab by overriding OnShowWindow to contain the following:
void MainFrame::OnShowWindow(BOOL bShow, UINT nStatus)
{
CFrameWndEx::OnShowWindow(bShow, nStatus);
if ((m_pOutlookBar != NULL) && bShow) {
//When the tab bar is shown, select the correctview
for (int tabIdx = 0; tabIdx < m_pOutlookBar->GetTabsNum(); tabIdx++) {
CString requiredLabel;
CString thisLabel;
requiredLabel.LoadString(IDS_OF_TAB); //The ID of the tab wanted
m_pOutlookBar->GetTabLabel(tabIdx,thisLabel);
if (requiredLabel.Compare(thisLabel) == 0) {
//If the tab label matches the one required
m_pOutlookBar->SetActiveTab(tabIdx); //set it as the active one.
break; //done.
}
}
}
}

MFC Spin/Edit Control

I am using an Spin Control with an Edit Control buddy. I have an OnEnChanged event as below
void MyClass::OnEnChangeSnrEdit()
{
UpdateData(TRUE);
wizard_data->wlan.min_snr = m_snr_spin.GetPos();
CheckValid();
}
CheckValid enables the next button on my dialog page if the value is within the range I want it to be. The problem I have is that if I manually delete the value from the Edit Control so it is blank then GetPos above returns 0. 0 is within the range I allow and so my Next button is enabled and the value 0 is set when there is actually no value in the Edit Control.
How do I solve this issue?
Simply check the Contents of the edit Control first. Only if it is not empty, then get the spin button Control.
But why to relay on the value of the spin Control. always use the value from the edit Control!

How to disable Edit control's focus on Dialog first launch?

Hello everybody reading this. Thanks in advance for your time.
One thing before question: I DO NOT use neither MFC nor Windows Forms, just WinApi in C++.
Well, I am making a polynomial calculator in Visual C++. I added a Dialog to it, which was created in resources (.rc file) using drag'n'drop method. I suppose there would be no such a problem if i created my Dialog with CreateWindowEx (but I don't want to).
My Dialog has a few of Edit Controls. Everything is fine except that when the Dialog is launched, one of Edit controls takes focus to be ready to take keyboard input.
I have included management of EN_KILLFOCUS (Edit sends it to parent when loses focus due to selecting another control).
Here I read from control to wstring (string of wide characters - _UNICODE is defined), use some kind of parser to verify this wstring and remove bad characters, and then put correct string into the same edit control. It works fine, but here is the source of my problem:
When there was no input, parser returns string "0" (not the NULL, string is just set to "0"), as if control had focus and then lost it even before I clicked anything in Dialog.
Due to that, and something else (this is what I have to figure out), at the Dialog launch parser puts this string "0" to edit.
I want to make my edit not be able to take input from keyboard until i click one of the Edits (including this one).
If it is not possible, I want to clear the whole text at the beginning of dialog (being able to take input is not a problem, I just want to prevent parser from entering string "0" at the beginning)
My code:
In DlgProc I have:
//up here is switch to manage all controls
case MyEditID: // here is ID of one of my edits from resources
switch (HIWORD(wParam))
{
case EN_KILLFOCUS: // edit lost focus - another control selected
if (LOWORD(wParam)==MyEditID) //necessary to determine if
// one of allowed Edits sent this message
// because I have also other Edits
{
GetDlgItemText(hPanel, LOWORD(wParam), MyTempWcharArray, 100);
MyTempString.assign(MyTempWcharArray);
w1 = polynomial(MyTempWcharArray); // parser takes the string
// and removes bad chars in constructor
// polynomial is my class - you don't have to care of it
// w1 is declared before as object of polynomial class
MyTempString = w1.ConversionToString();
SetDlgItemText(hDialog, LOWORD(wParam), sw1);
}
break;
}
break;
does it matter what integer number is set to Edit's ID?
I know SetFocus(), and WM_SETFOCUS message. In this case I just can't get this working.
If i haven't included something important to make you see my point please let me know. I'm sorry I'm just a newbie in WinAPI world.
EDIT:
For those with a similar problem: Do not do this:
I made an workaround with global variable ProcessKillFocus set to false indicating that instructions in message management should not be processed, except that at the end (just before break;) I am changing it to true, so next time and later it will be processed:
case EN_KILLFOCUS:
if (ProcessKillFocus && LOWORD(wParam)==MyEditID)
{
// first time global ProcessKillFocus is false so all this is skipped
// 2nd time and later do all the stuff
}
ProcessKillFocus = true;
break;
Huge thanx to Sheyros Adikari for making my question easy to understand!!!
Huge thanx to patriiice for simple answer on a huge messing question!!!
ANSWER:
BTW: patriiice, I tried this:
case WM_INITDIALOG:
SetFocus(GetDlgItem(hDialog, Desired_Control_ID));
return (INT_PTR)FALSE;
break;
IT JUST WORKS!!!
You have to return FALSE to WM_INITDIALOG message and set the correct focus by yourself.

Validation in QSpinBox

I have QSpinBox which should take only odd numbers, so I've set initial value to 3 and step to 2.
QSpinBox* spinBox = new QSpinBox;
spinBox->setValue(3);
spinBox->setSingleStep(2);
When I'm using spin box arrows to modify value everything is ok. But when I input value from keyboard it can take not odd numbers to.
So is it possible to set validation which fulfills my requirements without inheriting QSpinBox and redefining its validate method?
My current solution is checking in slot if the value is odd:
void MyWidget::slotSetSpinBoxValue(int value)
{
if(value%2 != 0)
{
//call function which takes only odd values
}
else
{
//here I want to show some kind off message that value can only be odd
//call function with --value parameter
}
}
Second question is how to show some tip for QSpinBox? I would like to show tip like tool tip is shown with message that QSpinBox value should be odd. I've found statusTip property in QWidget but cant find example how to use it.
You can connect to the editingFinished signal and fix it:
void Obj::onSpinEditFinished()
{
int val = ui->spinPoints->value();
if(val % 2 == 0)
ui->spinPoints->setValue(val-1);
}
With respect to Richard's comment, I think that ctrl->setKeyboardTracking(false) would get around the checking that would otherwise happen on each keystroke, and allow the validation only to happen at the end.
I think the correct answer doesn't work perfectly. It makes you unable to input values like "12", because the value changed singal will be triggered when "1" was input and it will be corrected to "0" as 1 is an odd numer.
The fix could be using a timer to correct the values in the spinbox. E.g. we restart a timer with (500ms) timout once we received the valueChanged signal(The timer will only triggered once if you type quickly enough). And we check and correct the input in the timers timeout slot.
In python I solved this as follows using the editingFinished property of the spinbox. This only fires a signal when you hit enter or move the focus away from the box. In python I had to pass the function references or the value passed is not the updated one but the one at initialization.:
class SpinboxExample:
def __init__(self)
spinbox = QSpinBox()
spinbox.editingFinished.connect(
lambda value=spinbox.value, set_spinbox_val=spinbox.setValue:
self.value_changed_spinbox(value,set_spinbox_val, set_slider_val)
)
I then had a callback function which checked whether number was odd and if not altered the value in the spinbox to make it odd.
def value_changed_spinbox(self, get_value,set_spinbox_value):
value=get_value()
if value % 2 == 0:
value += 1
set_spinbox_value(value)
Hope that helps.
Well you can make a workaround using the valueChanged() slot:
void MainWindow::on_spinBox_valueChanged(int arg1)
{
if( arg1 % 2 == 0)
{
//for even values, show a message
QMessageBox b;
b.setText("Only odd values allowed!");
b.exec();
//and then decrease the value to make it odd
ui.spinBox->setValue( arg1 - 1 );
}
}
Now if you want to keep the old value in case the used enters an even number, you will have to either inherit from QSpinBox, or use an event filter to catch key press events, and act before the value gets changed.
To show the message when the user hovers his/her mouse over the spinbox, you will need to set the box's toolTip, which holds the string that will be shown:
UPDATE:
If you don't want a message box, you can:
use QStatusBar. It can display messages which only last for some amount of time (that you pass it). The downside of it is that the message will appear on the bar on the bottom of the window, instead of being close to the spinbox.
Place a label under the spinbox. Set the label's text to something like "only odd values are allowed" when the user enters an invalid value, and set an empty string when the user enters a good value. You could also do this dynamically:
The user inputs a wrong value
Create a QLabel with the warning text, and set Qt::WA_DeleteOnClose flag, so the label will delete itself when closed.
Create a QTimer with singleShot, and set it to fire after a couple of seconds (when you want the message to dissapear)
Connect the timer's signal to the label's close() slot. When the timer will expire, the label will be closed, and, thanks to WA_DeleteOnClose, will be deleted.

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