Working with ListView in C++ - c++

I got a stupid question on ListView Control usage.
I created a Windows Form App in VS2005. No I dragged a ListView Control from the toolbox. I want to implement my code to show some content(including both columns and rows).
I know a little of MFC knowledge. I am not sure I must study the past MFC CListCtrol knowledge to implement my application or I can just study the System.Windows.Forms::ListView simply.
I found a good sample working with ListView (but wrote in C#). Can I translate the sample code from C# to C++ in VS2005? If I can. Could you please give me some suggestions?
using System;
using System.Windows.Forms;
using System.Drawing;
public class ListView1 : Form {
ListView listView = new ListView();
public ListView1() {
listView.Dock = DockStyle.Fill;
PopulateListView();
this.Controls.Add(listView);
this.ClientSize = new Size(400, 200);
}
private void PopulateListView() {
// Set the view to show details.
listView.View = View.Details;
// Add columns
listView.Columns.Add("Author",
-2,
HorizontalAlignment.Center);
listView.Columns.Add("Title",
-2,
HorizontalAlignment.Left);
listView.Columns.Add("Price",
-2,
HorizontalAlignment.Left);
// Add items
ListViewItem item1 = new ListViewItem("Steve Martin");
item1.SubItems.Add("Programming .NET");
item1.SubItems.Add("39.95");
ListViewItem item2 = new ListViewItem("Irene Suzuki");
item2.SubItems.Add("VB.NET Core Studies");
item2.SubItems.Add("69.95");
ListViewItem item3 = new ListViewItem("Ricky Ericsson");
item3.SubItems.Add("Passing Your .NET Exams");
item3.SubItems.Add("19.95");
// Add the items to the ListView.
listView.Items.AddRange(
new ListViewItem[] {item1,
item2,
item3}
);
}
public static void Main() {
ListView1 form = new ListView1();
Application.Run(form);
}
}

Actually you don't need that much of your previous knowledge of MFC to implement ListView. C++ under .NET (in layman terms means WinForm applications), you can almost seamlessly translate C# code to C++. If I understood your question correctly, what you need to do is to make sure how objects and properties are accessed in C++ if you are developing a winforms app. Like in C# if you have Object.function, in C++ you may need to write Object::function, this is just an example. Definitely you would need to some more in depth knowledge to run things seamlessly.

Related

How can I inform views in separate windows when using MVC in a Qt/c++ project?

I use MVC pattern, sqlite database in my code. I want
to show my same
data in different views, in the separate windows at the same time. Also, I want to
update my data.
I implement the model in a class and I call the model function as needed.
QSqlRelationalTableModel* MW_main::relModel()
{
QSqlRelationalTableModel *FTRmodel=new QSqlRelationalTableModel;
FTRmodel->setTable("filename");
FTRmodel->setEditStrategy(QSqlTableModel::OnFieldChange);
FTRmodel->select();
return FTRmodel ;
}
void Tables::model()
{
MW_main *mwmain = new MW_main;
QSqlRelationalTableModel *FTRmodel=new QSqlRelationalTableModel;
FTRmodel = mwmain->relModel ();
}
My code is working. But when i change a data in a window, the others are not aware of updating.
How can i inform other views?

Accessing Qt / QML objects with C++

I'm working on a C++ Qt project that will eventually communicate with the serial port. One part of this is accessing QML objects in the C++ portion. I have code that can set properties of the QML, but accessing those features that are methods now has me stumped. View the following code:
object = view.rootObject();
rect = object->findChild<QObject *>("box");
rect->setProperty("color", "red"); // Verifies the object tree is accessible
viewer = object->findChild<QObject *>("viewer"); // Access the viewer text box
viewer->append("dummy text"); // OOPS! This doesn't compile!!!
Now, the type as a method setProperty(..), but how do you access methods of an object. "viewer" is a TextArea and I want to first do a selectAll(), then a cut() to clear the box.
The question here is how is this coded? Thanks all.
Of course it would not compile, QObject doesn't have an append() method.
If it is a C++ function, you will have to qobject_cast to the appropriate type that has it. This however is not always readily available for many of the stock QML types that are implemented in C++, and as C++ types they are not part of the public API and not generally intended for direct use by an end user.
If it is a JS function, you will have to use QMetaObject::invokeMethod. That will also work for C++ functions for which meta data has been generated. Which is also how setProperty() works, whereas setColor() would not work with a QObject* much like append() doesn't.
Last but not least, there is absolutely no good reason for you to be doing those kinds of things from C++. Using QML objects from C++ is poor design and an anti-pattern. You will only develop bad habits trying to do that. Such interactions must be limited to a clearly defined interface using signals, slots and properties. Generally speaking, it is OK for QML to reach into C++, because that only happens through an exposed interface, but the opposite way, even if possible, should not utilized.
Think of it like this - a car uses the engine, the engine doesn't use the car. And the engine control is interfaced through the starter key and the gas pedal, it is not used directly. The C++ stuff should be reserved to the application engine - the high performance or efficiency core logic, or the back-end, whereas the QML part is for the GUI/front-end.
The author's QML part may expose alias property to operate with desired text field content:
import QtQuick 2.0
import QtQuick.Controls 1.2
Item {
property alias viewerText: viewer.text // added
width: 350
height: 450
TextArea {
id: viewer
x: 8
y: 8
width: 223
height: 415
text: "text"
font.pixelSize: 12
objectName: "viewer"
}
Button {
id: open
x: 251
y: 8
text: "Open"
}
}
And then the author's C++ part can easily do:
auto* object = view.rootObject();
viewer = object->findChild<QObject *>("viewer");
viewer->setProperty("viewerText", "dummy text"); // using the new property added
Using the posted answer here using the invoke method, here's the solution that works:
// C++ Code to call function reset()
QMetaObject::invokeMethod(object, "reset");
// QML code to select all text the delete it
function reset() {
viewer.selectAll()
viewer.cut()
}

Weird behavior when switching view between C++ and QML

I'm currently working on a project using Qt 5.0.2 on an embedded linux (ARM Cortex A9).
The main UI interface is developped in QML but I need to be able to hide this view to show a QWebView directly in C++.
I coded a simple view controller in c++ who hide()/show() the QML view and the many instances of QWebView.
The hiding/showing method work fine but when i show back the QML view, it's very instable. QML object are visible (or not visible :p) when they should not and the focus are buggy too. Object are draw in the wrong position too.
I try several methods :
-Initialize the focus/visible property of the differents objects everytime I show the QML view.
-use .setSource() everytime before showing the view
-try to update() the differents object thank to rootObject() before showing the view.
Did anyone have a tips to make the QML view functionnal again after a switch to a c++ view ?
thank.
there is probably a better way but,
you could probably do something like this (I have not tested this):
note: if the slot implementation is wrong (bad math) it will result in infinite recursion.
//this code could probably be in the constructor
real widthOverHeightRatio = 2;//set this value to what you want, or what it is when user first presses shift depending on the use case.
QObject::connect(this, SIGNAL(widthChange()), this, SLOT(onWidthChanged()));
QObject::connect(this, SIGNAL(heightChanged()), this, SLOT(onHeightChanged()));
//don't forget to define these slots in the header
//implemented slots
void MyClass::onWidthChanged()
{
if(width/height!=widthOverHeightRatio){
height = width/widthOverHeightRatio;
}
}
void MyClass::onHeightChanged()
{
if(width/height!=widthOverHeightRatio){
width = height*widthOverHeightRatio;
}
}

Model View Controller Design pattern Code Example

I was studying the Model-View-Controller design pattern and i understand the concept behind the pattern theorotically, but I wanted to get a peek at how one would actually put it to practice.
Wikipedia mentions Wt - Web toolkit, CppCMS and some other standard implementations which use the pattern however I have not been familiar with these, and I was just hoping and
will be really grateful If anyone can provide some sample code(hopefully C++) which implements the pattern and explains the theory of the pattern being put to practice.
Here's a quick example I made (didn't try compiling it, let me know if there's errors):
class Button; // Prewritten GUI element
class GraphGUI {
public:
GraphGUI() {
_button = new Button("Click Me");
_model = new GraphData();
_controller = new GraphController(_model, _button);
}
~GraphGUI() {
delete _button;
delete _model;
delete _controller;
}
drawGraph() {
// Use model's data to draw the graph somehow
}
...
private:
Button* _button;
GraphData* _model;
GraphController* _controller;
};
class GraphData {
public:
GraphData() {
_number = 10;
}
void increaseNumber() {
_number += 10;
}
const int getNumber() { return _number; }
private:
int _number;
};
class GraphController {
public:
GraphController(GraphData* model, Button* button) {
__model = model;
__button = button;
__button->setClickHandler(this, &onButtonClicked);
}
void onButtonClicked() {
__model->increaseNumber();
}
private:
// Don't handle memory
GraphData* __model;
Button* __button;
};
Ignoring the implementation of Button, basically this program will use GraphGUI to display a graph that will change when a button is pressed. Let's say it's a bar graph and it will get taller.
Since the model is independent of the view (the button), and the controller handles the communication between the two, this follows the MVC pattern.
When the button is clicked, the controller modifies the model via the onButtonClicked function, which the Button class knows to call when it is clicked.
The beauty of this is since the model and view are completely independent, the implementation of each can drastically change and it won't affect the other, the controller might simply have to make a few changes. If the model in this case calculated some result based off some database data, then clicking the button could cause this to happen, but the button implementation wouldn't have to change. Or, instead of telling the controller when a click occurs, maybe it can tell the controller when the button is moused-over. The same changes are applied to model, regardless of what triggered the changes.
A simple text editor could be designed based on MVC. Think of the string class as the model, where data is stored. We might have a class called SimpleTextView which displays the text in the string attached to it, as it is. A class called KeyboardEventHandler can act as the controller. The controller will notify the view about new keyboard events. The view in turn modifies the model (like appending or removing text). The changes in the model is reflected on all views attached to it. For instance, there might be another view called HtmlView attached to the string object manipulated from within the SimpleTextView. If the user enters valid HTML tags in the SimpleTextView, the HtmlView will display the formatted output - real-time.
There are couple of complete MVC examples, plus discussion, in ch 2 of an introduction to programming in Python 3.x that I wrote (I've not completed ch 3 etc., that project's been on ice for some time -- Python community really like angry swarm of bees when discovered I'd written that Python was perhaps not suitable for very large scale development, so it became difficult to get sensible feedback). It's available in PDF format from Google Docs. I don't know how well it maps to common MVC implementations, I was mostly concerned with getting the general idea across. :-)
Cheers & hth.,
PS: There's a nice table of contents in the PDF file but Google Docs doesn't show it. You'd need to dl and use Foxit or Acrobat or some other PDF viewer. I think there's a separate viewable TOC at Google Docs, though, haven't checked and don't remember whether updated.
PPS: Forgot to mention, the MVC image processing example near the end has nice pic of Lena Söderberg! :)
Code is the best approach to understand and learn Model View Controller:
Here is a simple JS example (from Wiki)
/** Model, View, Controller */
var M = {}, V = {}, C = {};
/** Model stores data */
M.data = "hello world";
/** View controls what to present */
V.render = (M) => { alert(M.data); }
/** Controller bridges View and Model */
C.handleOnload = () => { V.render(M); }
/** Controller on Windows OnLoad event */
window.onload = C.handleOnload;
Here is a detailed post in C/C++
Model-View-Controller Explained in C++

Using a QListView or similar effectively in Qt4

I am slowly getting used to using the Qt4 GUI framework. In a project I am working on, I need to be able to add/edit/remove Team objects in a list. Coming from a C#.NET perspective, I would do something like
List<Team> teams = new List<Team>();
teamsListBox.DataSource = teams;
teamsListBox.DisplayMember = "Name";
Then use buttons on the form to do the adding/removing/editing.
But, from what I can tell, there is no easy way to do this in Qt. I have looked over the documentation for QListView, QListWidget, QStandardItemModel, etc. but I cannot figure out how to get the equivalent Qt code for the C#.
My objective is to show the Teams in a list box of some kind, then be able to add/remove/edit the Teams underneath it at runtime.
How would you do this?
You should have a look at QAbstractItemModel and QStandardItemModel or create a customized TeamItemModel class for your teams that inherits from QAbstractItemModel. Those customized class will manage how the items are displayed in the Widget like QListView.
A simple for QString item example with QStringList:
QStringList list;
list << "item1" << "item2" << "item3" << "item4" << "item5";
ui->listView->setModel(new QStringListModel(list));
Then adding/removing/updating a Team should be easier than what you have tried.
Hope that helps.